ArrayList of my objects, indexOf problem

后端 未结 4 1539
一个人的身影
一个人的身影 2021-01-20 12:04

I have problem with Java\'s ArrayList. I\'ve created an Object, that contains two attributes, x and y. Now I\'ve loaded some object in my ArrayList. Problem is that I don\'t

4条回答
  •  遇见更好的自我
    2021-01-20 12:38

    I usually just use a map if i want to be able to fetch an object out of a collection based on one specific attribute value. I find that cleaner than having to iterate over lists.

    Map map = new HashMap();
    
    map.put(o1.getX(), o1);
    map.put(o2.getX(), o2);
    

    now, if i want the object that has an x-value of "foo", all it takes is

    Object desiredObject = map.get("foo");
    

    if order is important, consider a LinkedHashMap.

提交回复
热议问题