mardi 22 mars 2016

Java, First Item of ArrayList bugs when using String equals method

I have following classes (unnecessary details omitted):

class Person {
    public String name;
    public int id;

    public Person(String name, int id){
        this.name = name;
        this.id = id;
    }

    public void whoAmI(){
        System.out.println("I'm a person!");
    }
}

class Student extends Person {

    public Student(String name, int id){
        super(name, id);
    }

    public void whoAmI(){
        System.out.println("I'm a student!");
    }
}

class Teacher extends Person {

    public Student(String name, int id){
        super(name, id);
    }

    public void whoAmI(){
        System.out.println("I'm a teacher!");
    }

}

Now, I have an ArrayList, which holds all Teachers and Students. For example:

ArrayList<Person> people = new ArrayList<Person>();
Teacher t = new Teacher("John", 1);
people.add(t);
Student s = new Student("Dave", 2);
people.add(s);

At this point, I'm searching the arraylist and try to find out if a person with a specific name is a student or a teacher.

Person p = null;
for(int i=0; i<people.size(); i++){
    p = people.get(i);
    if(p.name.equals("John")){
        break;
    }
}

p.whoAmI();

As you can see, this should print

I'm a Teacher!

But it always prints

I'm a Student!

If I add the student first, or another item, it works correctly. But when the searched item was the first element of the arraylist, equals() method simply not working.

What's happening here?



Java, First Item of ArrayList bugs when using String equals method

Aucun commentaire:

Enregistrer un commentaire