【问题标题】:In Collections, how can i get the index using the indexOf method in the following example在 Collections 中,如何使用以下示例中的 indexOf 方法获取索引
【发布时间】:2015-05-22 08:20:52
【问题描述】:
    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 的其余对象没有引用,我不太确定如何检索它们的索引。请帮忙,非常感谢。

【问题讨论】:

    标签: java arraylist collections indexof


    【解决方案1】:

    如果您在 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).
    

    【讨论】:

    • 你能添加一个例子吗?我对它真的很感兴趣(解决问题的示例),我只能考虑通过列表进行迭代并获取每个对象的索引,其中它的名称字段对应于搜索的对象。
    • 我认为 OP 没有理解您的解决方案,他不接受答案的原因是什么。
    • 不知道为什么,他不再回复了。如果他还有问题,他可以在这些 cmets 中写,我猜他离线了:/
    • @Fernando Garcia,感谢您的回答,但我只想知道如何获得该对象的索引 - myFruitList.add(new Fruit("peach")); ***我的意思是-特别是在这种情况下-该对象没有在任何地方引用,所以如果我要使用 indexOf 方法,我该如何获取索引
    • 如果您创建了我上面写的hashCodeequals 方法,那么myFruitList.indexOf(new Fruit("peach")); 将返回索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多