View Javadoc
1   package de.dlr.shepard.util;
2   
3   import com.fasterxml.jackson.annotation.JsonIgnore;
4   import java.util.List;
5   
6   @FunctionalInterface
7   public interface HasId {
8     /**
9      * Returns a specific unique identifier for this object
10     *
11     * @return String of the unique identifier
12     */
13    @JsonIgnore
14    String getUniqueId();
15  
16    /**
17     * This function compares two lists of objects. These lists are equal if both
18     * are sorted in the same way and each object is equal when compared by its
19     * unique ID. Other attributes are ignored.
20     *
21     * @param a The first list
22     * @param b The second list
23     * @return True of both lists are equal
24     */
25    static boolean equalsHelper(List<? extends HasId> a, List<? extends HasId> b) {
26      if (a == null && b == null) return true;
27      if (a == null || b == null) return false;
28      if (a.size() != b.size()) return false;
29      // TODO: Should we sort these lists?
30      for (int i = 0; i < a.size(); i++) {
31        if (!equalsHelper(a.get(i), b.get(i))) return false;
32      }
33      return true;
34    }
35  
36    /**
37     * This function compares two objects. These objects are equal if their unique
38     * ID is equal. Other attributes are ignored.
39     *
40     * @param a The first object
41     * @param b The second object
42     * @return True if both objects are equal
43     */
44    static boolean equalsHelper(HasId a, HasId b) {
45      if (a == null && b == null) return true;
46      if (a == null || b == null) return false;
47      return a.getUniqueId().equals(b.getUniqueId());
48    }
49  
50    /**
51     * This function calculates the hash code of a list of objects. Only the unique
52     * ID is included in the calculation.
53     *
54     * @param a The list of objects
55     * @return The calculated hash code
56     */
57    static int hashcodeHelper(List<? extends HasId> a) {
58      if (a == null) return 0;
59      final int prime = 31;
60      int result = 1;
61      for (HasId element : a) {
62        result = prime * result + hashcodeHelper(element);
63      }
64      return result;
65    }
66  
67    /**
68     * This function calculates the hash code of a object. Only the unique ID is
69     * included in the calculation.
70     *
71     * @param a The object
72     * @return The calculated hash code
73     */
74    static int hashcodeHelper(HasId a) {
75      if (a == null) return 0;
76      return a.getUniqueId().hashCode();
77    }
78  }