When add elements to the list (ArrayList
) it does not perform any check on the existing element to check whether it is new element or already present. It will not be possible to use List
and get the desired behavior directly.
You can use the Set
collection for storing only the unique User
instance based on the name
attribute of it.
It is using the HashSet<User>
implementation, which uses the hashcode()
of the incoming object for storing them at a certain location. If the element is already present then it uses the equals()
to compare the two objects.
Here is an sample example:
public class User {
private String name;
public User(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof User))
return false;
User user = (User) obj;
return user.name.equals(this.name);
}
@Override
public int hashCode() {
return name.hashCode() ;
}
}
class UserMain {
public static void main(String[] args) {
Set<User> set = new HashSet<>();
set.add(new User("A"));
set.add(new User("B"));
set.add(new User("A"));
System.out.println(set.size());
}
}