+ public Ranking validate() throws IllegalArgumentException
+ {
+ if (this.entries.length > MAX_ENTRIES)
+ throw new IllegalArgumentException("Invalid Ranking: a valid ranking cannot have more entries than " + MAX_ENTRIES );
+
+ Set<String> seenWords = new HashSet<>();
+ long lowesCounting = Long.MAX_VALUE;
+
+ for (int i=0; i<this.entries.length; i++)
+ {
+ Entry entry = this.entries[i];
+
+ if (seenWords.contains(entry.getKey()))
+ throw new IllegalArgumentException("Invalid Ranking: Multiple occurrences of word -> " + entry.getKey());
+ if (entry.getCounter() > lowesCounting)
+ throw new IllegalArgumentException("Invalid Ranking: Entries are not sorted correctly");
+
+ seenWords.add(entry.getKey());
+ lowesCounting = entry.getCounter();
+ }
+
+ return this;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ return true;
+ if (o == null)
+ return false;
+ if (!(o instanceof Ranking))
+ return false;
+
+ Ranking other = (Ranking)o;
+
+ if (other.entries.length != entries.length)
+ return false;
+
+ if (entries.length == 0)
+ return true;
+
+ int i = 0;
+ Set<String> myWordsWithCurrentCount = new HashSet<>();
+ Set<String> otherWordsWithCurrentCount = new HashSet<>();
+ Entry myEntry = entries[i];
+ long currentCount = myEntry.getCounter();
+ myWordsWithCurrentCount.add(myEntry.getKey());
+ while (true)
+ {
+ Entry otherEntry = other.entries[i];
+ if (otherEntry.getCounter() != currentCount)
+ return false;
+ otherWordsWithCurrentCount.add(otherEntry.getKey());
+ if (++i >= entries.length)
+ return myWordsWithCurrentCount.equals(otherWordsWithCurrentCount);
+ myEntry = entries[i];
+ if (myEntry.getCounter() != currentCount)
+ {
+ if (!myWordsWithCurrentCount.equals(otherWordsWithCurrentCount))
+ return false;
+ currentCount = myEntry.getCounter();
+ myWordsWithCurrentCount.clear();
+ otherWordsWithCurrentCount.clear();
+ }
+ myWordsWithCurrentCount.add(myEntry.getKey());
+ }
+ }
+