Nexusfactor
Nexusfactor

Reputation: 13

Finding index of more than one object

I create this code just for my own understanding. I have a person class and a List to store all my Person objects. I added the same object twice to illustrate my question. How do I find the index of those objects?

How do I find the indexes of the two Andy Bernards?

public class Person {

    private String firstName;
    private String lastName;

    public Person(String firstName,String lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;

    }

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override public String toString()
    {
        return String.format(this.firstName + " " + this.lastName);  
    }
}



List<Person> deletePeople = new ArrayList<Person>();
Person createPerson = new Person("Andy","Bernard"); 
Person createTwo = new Person("Micheal","Scott");
deletePeople.add(createPerson);           
deletePeople.add(createTwo);         
deletePeople.add(createPerson);
/* for (Person display : deletePeople) {
    if(display.getFirstName().equals("Andy")) {
        System.out.println(deletePeople.indexOf(display));
    }
} */ 
}

Upvotes: 0

Views: 250

Answers (2)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

If what you really want is a list of indexes into the list where objects match your criteria, and there can be more than one, then you will need to iterate the list yourself, and save the indexes to some sort of list.

If what you want is simply to delete the matching items, then you can use java.util.Iterator (see http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) to iterate over the collection, and invoke the Iterator's remove() method on each matching object as you encounter it.

Upvotes: 0

La-comadreja
La-comadreja

Reputation: 5755

Firstly, add .equals() and .hashCode() methods to class Person so you can identify a Person object as being the same.

Second, use indexOf() and lastIndexOf() methods in class List to find the first and last Andy Bernard objects.

Upvotes: 1

Related Questions