Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()

前端 未结 8 1134
庸人自扰
庸人自扰 2020-11-27 03:50

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

8条回答
  •  攒了一身酷
    2020-11-27 04:25

    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.

提交回复
热议问题