JAL-1800 SearchResults.equals() to allow smarter mouseover of codons
[jalview.git] / src / jalview / datamodel / SearchResults.java
index 2a33f6c..3948ba0 100755 (executable)
@@ -36,6 +36,10 @@ public class SearchResults
 
   private List<Match> matches = new ArrayList<Match>();
 
+  /**
+   * One match consists of a sequence reference, start and end positions.
+   * Discontiguous ranges in a sequence require two or more Match objects.
+   */
   public class Match
   {
     SequenceI sequence;
@@ -92,13 +96,44 @@ public class SearchResults
       // convert start/end to base 0 (with bounds check)
       final int from = Math.max(start - 1, 0);
       final int to = Math.min(end, chars.length + 1);
-      return String.valueOf(Arrays.copyOfRange(chars, from, to));
+      // return String.valueOf(Arrays.copyOfRange(chars, from, to));
+      return String.valueOf(from)
+              + String.valueOf(Arrays.copyOfRange(chars, from, to));
     }
 
     public void setSequence(SequenceI seq)
     {
       this.sequence = seq;
     }
+
+    /**
+     * Hashcode is the hashcode of the matched sequence plus a hash of start and
+     * end positions. Match objects that pass the test for equals are guaranteed
+     * to have the same hashcode.
+     */
+    @Override
+    public int hashCode()
+    {
+      int hash = sequence == null ? 0 : sequence.hashCode();
+      hash += 31 * start;
+      hash += 67 * end;
+      return hash;
+    }
+
+    /**
+     * Two Match objects are equal if they are for the same sequence, start and
+     * end positions
+     */
+    @Override
+    public boolean equals(Object obj)
+    {
+      if (obj == null || !(obj instanceof Match))
+      {
+        return false;
+      }
+      Match m = (Match) obj;
+      return (this.sequence == m.sequence && this.start == m.start && this.end == m.end);
+    }
   }
 
   /**
@@ -281,4 +316,30 @@ public class SearchResults
     }
     return result.toString();
   }
+
+  /**
+   * Hashcode is has derived from the list of matches. This ensures that when
+   * two SearchResults objects satisfy the test for equals(), then they have the
+   * same hashcode.
+   */
+  @Override
+  public int hashCode()
+  {
+    return matches.hashCode();
+  }
+
+  /**
+   * Two SearchResults are considered equal if they contain the same matches in
+   * the same order.
+   */
+  @Override
+  public boolean equals(Object obj)
+  {
+    if (obj == null || !(obj instanceof SearchResults))
+    {
+      return false;
+    }
+    SearchResults sr = (SearchResults) obj;
+    return ((ArrayList<Match>) this.matches).equals(sr.matches);
+  }
 }