Java - how best to perform operations with multiple (e.g. keepAll) based on user comparison

I have two sets containing the same types of objects. I would like to have access to the following:

  • intersection of two sets
  • objects contained in set 1, not in set 2
  • objects contained in set 2, not in set 1

My question is about how best to compare two sets to get the right views. The class in question has many id properties that can be used to uniquely identify this object. However, the class also has many properties that describe the current status of the object. These two sets can contain objects that correspond according to identifiers, but which are in a different state (and as such, not all properties are equal between two objects).

So - what is the best way to implement your decision. To implement the equals () method for a class that does not take into account status properties and only looks at id properties, it seems not very true for the name "equals" and may be confusing later. Is there a way to provide a method by which comparisons are made for given methods?

In addition, I would like to be able to access the 3 views described above without changing the source sets.

All help is much appreciated!

+3
source share
3 answers

Short version: implements equalsbased on an entity key, not state.

: , equals, . , "" (, Integer String Address), , . , ( ), . ( ) . , . , , Set Map, , , , Set/Map .

equals, , Guava :

Set<Foo> notInSet2 = Sets.difference(set1, set2);
Set<Foo> notInSet1 = Sets.difference(set2, set1);

, .

+3

(Edit: - TreeSet, . (, TreeSet) Comparator , - , .)

(.. CompareTo(), HashCode() Equals()), -, , , , HashSet -.

+4

, ++ set type, . Java Map, , , -. ( , ++ set , - , Java TreeSet, Comparator.) , , .

, . , , , ; , Map , -, . .

, ; . -, , . , , , .

, , , , . .

+1

All Articles