tyczj
tyczj

Reputation: 73731

Checking a ArrayList of a class for duplicates

I have an ArrayList of a class that holds information, and I want to add to objects to this list. I want to check to see if that list already contains a number before adding it to a list.

Normally if it were just a list of strings I would just do something like this

if(!list.contains("this string")){
    list.add("this string");
}

but since this is a class, it has more than one variable per index.

An example of the class world be this:

private class From{
    private long threadID;
    private long date;
    private String address;
    private String body;
    private int type;
    private long id;

    @Override
    public boolean equals(Object obj){
        if(obj != null){
            if(getClass() != obj.getClass()){
                return false;
            }else{
                final From from = (From)obj;
                if((this.address != null) ? (from.address != null) : !this.address.equals(from.address)){
                    return false;
                }
            }
        }else{
            return false;
        }
        return true;
    }
}

I want to see if there is already an entry with the same number, so am I going to have to manually loop through each index and check, or is there an easier way of doing what I want to do?

EDIT:

how i call it

HashSet<From> addresses = new HashSet<From>();
From f = new From();
                f.setAddress(messages.getString(3));
                f.setBody(messages.getString(0));
                f.setDate(messages.getLong(2));
                f.setThreadId(messages.getLong(1));
                f.setType(1);
                if(!addresses.contains(f.address)){
                    addresses.add(f);
                }

Upvotes: 1

Views: 205

Answers (4)

rgettman
rgettman

Reputation: 178253

You can still use the contains method; A List uses the equals method to determine if the item exists in the list. But you must override equals in your Info object.

Upvotes: 0

PermGenError
PermGenError

Reputation: 46408

Another way would be to override equals() for Info object such that two Info objects are equal if they both have the same number. before adding the element into the list just do the equals() test .

Upvotes: 1

cowls
cowls

Reputation: 24334

Use a Set instead of a List. Sets dont allow duplicates

http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html

You will also need to override equals in your class so the Set knows if two objects are equal

Example of overriding equals can be found here: How to override equals method in java

Upvotes: 4

Dan D.
Dan D.

Reputation: 32391

You have to override equals(Object o) for this. This is the place where you need to define the logic that would define the equality between two objects.

It is good practice to override hashCode() as well. Read more in the Javadocs for Object.

Upvotes: 1

Related Questions