I have an array of objects and I want to concatenate it with another array of objects, except that objects that have same id\'s. That objects are used in many places in the
HashingStrategy is the concept you're looking for. It's a strategy interface that allows you to define custom implementations of equals and hashcode.
public interface HashingStrategy
{
int computeHashCode(E object);
boolean equals(E object1, E object2);
}
As others have pointed out, you can't use a HashingStrategy
with the built in HashSet
or HashMap
. Eclipse Collections includes a set called UnifiedSetWithHashingStrategy
and a map called UnifiedMapWithHashingStrategy
.
Let's look at an example. Here's a simple Data
class we can use in a UnifiedSetWithHashingStrategy
.
public class Data
{
private final int id;
public Data(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
// No equals or hashcode
}
Here's how you might set up a UnifiedSetWithHashingStrategy
and use it.
java.util.Set set =
new UnifiedSetWithHashingStrategy<>(HashingStrategies.fromFunction(Data::getId));
Assert.assertTrue(set.add(new Data(1)));
// contains returns true even without hashcode and equals
Assert.assertTrue(set.contains(new Data(1)));
// Second call to add() doesn't do anything and returns false
Assert.assertFalse(set.add(new Data(1)));
Why not just use a Map
? UnifiedSetWithHashingStrategy
uses half the memory of a UnifiedMap
, and one quarter the memory of a HashMap
. And sometimes you don't have a convenient key and have to create a synthetic one, like a tuple. That can waste more memory.
How do we perform lookups? Remember that Sets have contains()
, but not get()
. UnifiedSetWithHashingStrategy
implements Pool
in addition to MutableSet
, so it also implements a form of get()
.
Note: I am a committer for Eclipse Collections.