indexOf
int indexOf(Object o)返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。更确切地讲,返回满足 (o==null ? get(i)==null : o.equals(get(i))) 的最低索引 i;如果没有这样的索引,则返回 -1。 参数:
o - 要搜索的元素 
返回:
此列表中第一次出现的指定元素的索引,如果列表不包含该元素,则返回 -1 
抛出: 
ClassCastException - 如果指定元素的类型和此列表不兼容(可选) 
NullPointerException - 如果指定的元素是 null,并且此列表不允许 null 元素(可选)
   由api我分析,如果o !=null 则equals会影响此方法的返回值,故我作此测试。   package com.xuz.csdn.july05;public class Product {
private int id;
private String name;

public Product(int id,String name){
this.id = id;
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}

public boolean equals(Product p){
if (this.id == p.getId()) {
return true;
} else {
return false;
}
}
}
package com.xuz.csdn.july05;import java.util.ArrayList;
import java.util.List;public class ProductApp { public static void main(String[] args) {
Product p1 = new Product(1,"a");
Product p2 = new Product(2,"b");
Product p3 = new Product(3,"c");

Product p2_ = new Product(2,"b");

List<Product> list = new ArrayList<Product>();
list.add(p1);
list.add(p2);
list.add(p3);

for (int i = 0; i < list.size(); i++) {
System.out.println(p2_.equals(list.get(i)));
}

System.out.println(list.indexOf(p2_));
}}
按照api应该返回1,为何返回-1
   

解决方案 »

  1.   

    你的equals是方法错了...参数应该是(Object obj)
      

  2.   


    学习了!  public boolean equals(Object o){
    //         if (this.id == p.getId()) {
    //             return true;
    //         } else {
    //             return false;
    //         }
         Product p = (Product)o;
         if (this.id == p.getId()) {
                return true;
            } else {
                return false;
            }
        
           }
      

  3.   


    对,系统调用的equals方法为equals(Object o)
    如果没覆盖这个方法,自然调用不到。