0

I want to add unique objects into list on the basis of property of object.

class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;

    Employee(long employeeId,String firstName,String lastName){
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

I want to insert object into list on the basis of unique 'employeeId' and 'firstName' , combination should be unique while inserting object into list.

1
  • Please add the code you use to add the instance to the list of Employee, and tell us which type is your list. Commented Mar 27, 2015 at 7:00

3 Answers 3

3

If you want certain containers to work that are able to prevent duplicates of your Employee from being added you need to define how equals is calculated in Employee.

public class Employee {
//...
    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder()
            // if deriving: .appendSuper(super.equals(obj))
            .append(employeeId, rhs.employeeId)
            .append(firstName, rhs.firstName)
            .append(lastName, rhs.lastName)
            .isEquals();
    }
}

If you want certain containers to work that are able to look up your Employee quickly you need to define how hashcode is calculated in Employee.

public class Employee {
//...
    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + employeeId;
        hash = hash * 31 + firstName.hashCode();
        hash = hash * 13 + lastName.hashCode();
        return hash;
    }
}

Most modern IDE's will offer a re-factoring to do this for you. Use the same fields in both so they change together.

Since you don't want duplicates you're best bet is to not use ArrayList but something that pays attention to the hash and will enforce uniqueness for you. Whenever I'm picking a container in java I look at this:

enter image description here

To have all of those available to you, you need to implement not only hashcode and equals but comparator as well.

Just to be clear, the point of the hash is to provide lookup speed. The point of equals is to define what objects are considered identical. The point of comparator is to provide an ordering for the objects.

If you want to include the less frequently used containers try this:

enter image description here

Sign up to request clarification or add additional context in comments.

14 Comments

Much better - but you are still not talking about equals(). And as I said: these two methods should both be overwritten.
According to the java doc of Set.add(E e): adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
Why is there no LinkedList here? Great graph though
@RobinHellemans You'll find your LinkedList in the bottom right corner
The first graph suggests ArrayList if you don't want duplicates, and you don't need to search the collection often? Sounds like nonsense to me.
|
1

This can be achieved by overwriting the methods equals() and hashCode() - then you can turn to existing java.util collection classes (like HashSet) that use these methods when comparing objects.

Comments

1

Here, equals() & hashCode() methods are overridden to meet the given requirements.

class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;

    Employee(long employeeId,String firstName,String lastName){
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public boolean equals(Object o){
        if(o == null) return false;
        if(!(o instanceof) Employee) return false;

        Employee other = (Employee) o;
        if(this.employeeId != other.employeeId)      return false;
        if(! this.firstName.equals(other.firstName)) return false;

        return true;
   }

    public int hashCode(){
        return (int) employeeId * firstName.hashCode();
    }
}

Here, if two Employee objects are equal, they will also have the same hash code. But, even still two Employee objects can be not equal having the same hash code.

Ex: The hash code is the employeeId is rounded down to an int. That means that many employee id's could result in the same hash code, but these Employee objects would still not be equal, since they don't have the same employee id.

4 Comments

Same here: It is bad style to only override equals() without overwriting equals(). And without telling Qasim that he should use a different data structure ... it would not work for him. And not providing any explanation - how is he supposed to learn from that?
@EddyG please check the complete solution.
@ViswanathD You are still missing to point out that he needs to use something else than a List ..
@ViswanathD You are still not mentioning at all that hashCode/equals are just "enabling" to use a data structure like HashSet. Just compare your answer the other two.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.