Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

hashCode() of arrays

807591May 10 2008 — edited May 12 2008
Hi,

I want to put some vectors into a set, so I wrote the following code:
Set<double[]> set = new HashSet<double[]>();
double[] x = new double[] { 1., 2., 3. },
         y = x.clone();
set.add(x);
set.add(y);
System.out.println(set.size()); // prints "2"
The problem is that the standard hashCode() implementation of java arrays does not take into account the array values. That's why the vectors x and y hash differently. My question: How can I change this behaviour? The only way I see would be to encapsulate the array into its own class and override the hashCode() method, e.g. using Arrays.hashCode(double[] x).

I think that's pretty ugly :-( Is there a better way to do this?

Thanks!
gogo_
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 9 2008
Added on May 10 2008
9 comments
505 views