A Mechanism for having different equals (physical equals and logical equals) on objects in Collection

北慕城南 提交于 2019-11-29 14:24:59

Your question doesn't really come across clearly, at least to me. If this doesn't answer it properly, could you re-word a little bit?

Within a given Collection concrete type, most equals implementations already do what you hint at. For instance:

    public boolean equals(Object o) {
        if (o == this)
            return true;

In this case, something like this might make sense.
You can easily override this:

    @Override
    public boolean equals(Object o) {
        if (o.getPrimaryKey() == this.getPrimaryKey()) 
            return true;
        return super().equals(o);

[test for nulls should be added] If you are creating standard collections, you can even anonymously override the equals method during construction.

If this doesn't do what you want, you could extend Collections yourself and override any of the methods there to do a similar thing.

Does that help?

lbalazscs

A late answer, but maybe it will be useful for someone...

The Guava Equivalence class is the same for equivalence as Comparator for comparing. You would need to write your own method for comparing the lists (there is no support in Guava for that), but then you could call this method with various equivalence-definitions.

Or you can roll your own interface:

interface Equalator<T> {
    boolean equals(T o1, T o2);
}

Again, you need to write your (trivial) method

boolean <T> listEquals(List<T> list1, List<T> list2, Equalator<T> equalator) {
    ...  
}

...but then you can reuse it with different ListEqualator implementations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!