gigs gigs - 5 months ago 10
Java Question

How to add object with unique field to Set

How can I fill a Set by objects with unique field ?

For example I have a class

Person
which has an unique field called
name
thus if I add to Set an object with duplicate name it should not be added.

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Person> objList = new HashSet<Person>();
objList.add(new Person("John", "New York", "Accountant"));
objList.add(new Person("Bill", "London", "Manager"));
objList.add(new Person("John", "New York", "Driver"));// this object should not be added

for(Person o : objList){
System.out.println(o.name);//here should printed only John and Bill
}
}
}

class Person {
String name;//must be unique
String city;
String position;

public Person(String c_name, String c_city, String c_position){
this.name = c_name;
this.city = c_city;
this.position = c_position;
}
}

Answer

In other words, you mean the person's name defines it's identity. You can produce such a behavior by overriding the equals(Object) and hashCode methods to include only it:

public class Person {
    // members, constructors, etc.

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Person)) {
            return false;
        }
        return name.equals(((Person)other).name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}