Java settings have multiple equality criteria
I have a special request. I need to delete the object list repeatedly according to the combination of equal standards
For example, two students are right about 1 Firstname and ID are the same or 2 LastName, class and emailid are the same
I'm going to use set to remove duplicates However, there is a problem: I can override the equals method, but the hashcode method may not return the same hash code for two equal objects
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if ((firstName.equals(other.firstName) && id==other.id) || (lastName.equals(other.lastName) && class==other.class && emailId.equals(other.emailId )) return true; return false; }
I can't override the hashcode method now because it returns the same hash code for two equal objects based on this equals method
Is there a way to de duplicate data according to multiple equality standards? I consider using list and then using the contains method to check whether the element already exists, but this increases the complexity of inclusion running in O (n) time I don't want to return exactly the same hash code for all objects, because it will only increase time and exceed the purpose of using hash code I have also considered using a custom comparator to sort items, but again I need at least o (n log n), plus a step to delete duplicates
So far, the best solution I have is to maintain two different sets, each corresponding to a condition, and use it to build a list, but it takes almost three times the memory I'm looking for a faster and more efficient way of memory because I'll handle a lot of records
Solution
You can make student comparable and use TreeSet A simple implementation of CompareTo may be:
@Override public int compareTo(Student other) { if (this.equals(other)) { return 0; } else { return (this.firstName + this.lastName + emailId + clazz + id) .compareTo(other.firstName + other.lastName + other.emailId + clazz + id); } }
Or create your own set implementation, such as a list containing different student objects. Check whether the students are equal each time you add them This will increase the complexity of O (n), so it can not be considered a good implementation, but it is very simple to write
class ListSet<T> extends AbstractSet<T> { private List<T> list = new ArrayList<T>(); @Override public boolean add(T t) { if (list.contains(t)) { return false; } else { return list.add(t); } } @Override public Iterator<T> iterator() { return list.iterator(); } @Override public int size() { return list.size(); } }