List<Student> l = new ArrayList<Student>();
Student是一个类,类里面包含两个变量,现在Student s = new Student("某人","某号");
如何判断在ArrayList的数组中存在一个除了地址其他和s一模一样的Student类(也就是里面的变量的值是某人和某号)??????

解决方案 »

  1.   

    Student类重写equals方法。
    或者用Student两个变量分别比较,两个对象的两个变量分别对应相等,则两个对象相等。
      

  2.   

    同意brightyq的回复,但是如果要提高搜索的速度,建议使用HashMap作为容器
      

  3.   

    Student类重写equals方法。
      while循环遍历对象用.equals(new Student("某人","某号"));比较 如果为ture 就存在
     
      

  4.   


    呃... ... 这个... ...楼主又没直接伸手要代码,顺便解释一下嘛
    1楼说的没错重写 Student 的 equals 方法,同时别忘了重写它的 hashCode 方法。
    hashCode 与 equals 的约定如下:
    http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29另外阅读 List 接口的 API:
    http://docs.oracle.com/javase/6/docs/api/java/util/List.html
      

  5.   

    ----------------------------Student Class--------------
    public class Student {
    private String name; private int number; public Student(String name, int number) {
    this.name = name;
    this.number = number;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public int getNumber() {
    return number;
    } public void setNumber(int number) {
    this.number = number;
    } @Override
    public boolean equals(Object o) {
    // TODO Auto-generated method stub
    Student s = (Student) o;
    if (o instanceof Student && this.getName().equals(s.getName())
    && this.getNumber() == s.getNumber())
    return true; return false;
    } @Override
    public int hashCode() {
    // TODO Auto-generated method stub
    return this.getNumber() * 3;
    }
    }
    ----------------------------Main Class--------------import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;public class TestStudent {
    public static void main(String[] args) { Student one = new Student("same", 20); Student lily = new Student("lily", 20); Student jack = new Student("jack", 20); Student two = new Student("same", 20);

    Student three = new Student("same", 20);

    Student four = new Student("same", 20);

    List<Student> l = new ArrayList<Student>(); l.add(one);
    l.add(two);
    l.add(three);
    l.add(four);
    l.add(lily);
    l.add(jack); Iterator it = l.iterator();
    it.next();
    for (Student stu : l) { while (it.hasNext()) { Student s = (Student) it.next(); if (stu.equals(s)) {
    System.out.println("The same student's name are : " + stu.getName());
    }

    }
    } }
    }
      

  6.   

    要自己重写equals() 方法哦!