gigs gigs - 1 year ago 40
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

which has an unique field called
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(;//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){ = c_name; = c_city;
this.position = c_position;

Answer Source

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.

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

    public int hashCode() {
        return name.hashCode();