javaduplicatesset.class-file

How to avoid storing duplicates in a Set if the objects type comes from a compiled .class file?


I am trying to store objects in a Set to avoid duplicates.

As this topic explains I need to @Override two methods: hashCode() and equals(Object obj).

The objects type that I am trying to store in the above Set comes from a compiled .class file and it doesn't have hashCode() and equals(Object obj) methods and either it's parents on inheritance chain (except Object).

Is there a way to store them in a Set to avoid duplicates?


Solution

  • If you cannot modify the objects, then you can wrap them.

    class EmployeeHolder {
      private final Employee employee;
      public int hashCode() { ... }
      public boolean equals(Object o) {
        if (!(o instanceof EmployeeHolder)) return false;
        ...
      }
    }
    Set<EmployeeHolder> set = new HashSet<>();