0

My program has to pass a lot of arrays between threads. I want a collection that can accept an array, and then a contains method will specify whether a Set/Map contains the array (i.e. it is a duplicate or has already been processed by the thread). I assume this collection would have to use Arrays.equals(a1, a2), because the Object.equals() method will not work on arrays. Is it possible to write a collection that works like this, or would it fail when autoboxing from, say, int[] to Integer[]?

Community
  • 1
  • 1
NobleUplift
  • 5,631
  • 8
  • 45
  • 87

1 Answers1

6

Use a wrapper for Array which overrides hashCode() and equals() like Arrays.asList().

BTW, you should avoid using arrays and opt for Collections whenever possible. I also recommend you use immutable data structures for multi-threading. Using a mutable object in a Set or as the key of a Map is a terrible idea anyways.

billc.cn
  • 7,187
  • 3
  • 39
  • 79
  • 1
    I would highly recommend storing that hashCode as a variable in that instance if you can. Looping through the elements every time you want the hash can be very costly. – Obicere Oct 09 '13 at 16:12
  • By wrapper, do you mean an extension of `Array`? Because it's a final class. – NobleUplift Oct 09 '13 at 16:13
  • Also, to clarify I do want to use a collection, but something like Set or Map. – NobleUplift Oct 09 '13 at 16:15
  • @NobleUplift Wrapper means a wrapper class. I.e. you always wrap the array in this class before you put it into the collection. I.e. instead of using `Set` you manually build up `Set>` by converting arrays to `List`s using `Arrays.asList()`. – billc.cn Oct 09 '13 at 16:20