Using an array as a key in a Map bad idea, because you cannot count on the fact that two arrays containing the same elements will have the same hash code and return true when comparing with equals .
One solution to the problem is to create a wrapper class for the array that implements the hashCode and equals methods:
private static class Element { public final short[] values; public Element(short[] values) { this.values = values; } @Override public boolean equals(Object obj) { if (obj instanceof Element) { return Arrays.equals(values, ((Element)obj).values); } return false; } @Override public int hashCode() { return Arrays.hashCode(values); } } public static void main(String[] args) { short[][] test = { { 1,2 }, { 3,4 }, { 1,2 }, { 3,4 }, { 1,2 }, { 3,4 } }; Set<Element> uniqueElements = new HashSet<>(); for (short[] group : test) { uniqueElements.add(new Element(group)); } List<short[]> result = new ArrayList<>(); for (Element element : uniqueElements) { result.add(element.values); } }
Instead of HashSet you can use LinkedHashSet , as well as LinkedList instead of ArrayList , to get unique elements is not important.
In Java 8, the main method might look like this:
short[][] test = { { 1,2 }, { 3,4 }, { 1,2 }, { 3,4 }, { 1,2 }, { 3,4 } }; List<short[]> result = Stream.of(test) .map(Element::new) .distinct() .map(e -> e.values) .collect(Collectors.toList());
If you need to add items to the queue one by one in a separate method, you can convert the source code like this:
public static void main(String[] args) { short[][] test = { { 1,2 }, { 3,4 }, { 1,2 }, { 3, 4 }, { 5,6 }, { 3,4 } }; Queue<Element> queue = new LinkedList<>(); for (short[] group : test) { addElement(group, queue, 10); } } private static void addElement(short[] array, Queue<Element> queue, int maxSize) { Element element = new Element(array); if (queue.contains(element)) { return; } while (queue.size() >= maxSize) { queue.poll(); } queue.add(element); }
There is, instead of blocking the addition of a duplicate, you need to add an element to the end of the queue, then instead
if (queue.contains(element)) { return; }
enough to use
queue.remove(element);
HashMapwatched? OrHashSet- JVic