在集合中,如何使用以下示例中的indexOf方法获取索引

时间:2015-05-22 08:20:52

标签: java arraylist collections indexof

    class Fruit{
      public String name;
      Fruit(String name){
        this.name = name;
        }
    }//end of Fruit

    class FruitList{
     public static void main(String [] arg5){
        List<Fruit> myFruitList = new ArrayList<Fruit>();
        Fruit banana = new Fruit("Banana"); 
    //I know how to get the index of this banana
        System.out.println("banana's index "+myFruitList.indexOf(banana));
 //But i'm not sure how can i get the indices for the following objects
        myFruitList.add(new Fruit("peach"));
        myFruitList.add(new Fruit("orange"));
        myFruitList.add(new Fruit("grapes"));
  }//end of main 

}//end of FruitList

由于我添加到ArrayList的其他对象没有引用,我不太确定如何检索它们的索引。请帮忙,非常感谢。

1 个答案:

答案 0 :(得分:6)

如果重新定义Fruit类中的equals和hashcode方法,则对象具有哪个引用无关紧要。 indexOfcontains等使用equals(...)方法来确定对象是否存在于集合中。

例如,您的Fruit类可能是这样的(我将您的public String name更改为私有):

public class Fruit {
    private String name;

    public Fruit(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 89 * hash + Objects.hashCode(this.name);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Fruit other = (Fruit) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return true;
    }

然后:

Fruit f = new Fruit("orange");
myFruitList.indexOf(f); // this should return the orange fruit index (would be 1 in your example).