HashCode() eines int[ ] Arrays

-ben-

Mitglied
hy!

wieso erhalte ich bei folgendem code-snippet nicht den selben HashCode?
Code:
int[] a1 = new int[]{1,2,3};
int[] a2 = new int[]{1,2,3};
System.out.println( a1.hashCode() );
System.out.println( a2.hashCode() );
Wie kann ich dies umgehen?

danke und gruss
ben
 
Hallo!

wieso erhalte ich bei folgendem code-snippet nicht den selben HashCode?
Weil das zwei unterschiedliche Instanzen sind und die hashCode() Implementierung von java.lang.Object verwendet wird.

Wenn du fuer int Arrays mit gleichen Inhalten den gleichen hashCode moechtest kannst du das beispielsweise so machen:
Code:
/**
 * 
 */
package de.tutorials;

import java.util.Arrays;

/**
 * @author Thomas
 *
 */
public class IntArrayHashCodeExample {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] a1 = new int[]{1,2,3};
		int[] a2 = new int[]{1,2,3};
		
		System.out.println(Arrays.hashCode(a1));
		System.out.println(Arrays.hashCode(a2));
	}
}

Gruss Tom
 
Hallo!

Na ja,
auf der einen Seite ist es ja kein Problem zu schauen wie da in Java 5 implementiert ist...:
Code:
	/**
	 * Returns a hash code based on the contents of the specified array.
	 * For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt>
	 * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
	 * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
	 *
	 * <p>The value returned by this method is the same value that would be
	 * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
	 * method on a {@link List} containing a sequence of {@link Integer}
	 * instances representing the elements of <tt>a</tt> in the same order.
	 * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
	 *
	 * @param a the array whose hash value to compute
	 * @return a content-based hash code for <tt>a</tt>
	 * @since 1.5
	 */
	public static int hashCode(int a[]) {
		if (a == null)
			return 0;
 
		int result = 1;
		for (int element : a)
			result = 31 * result + element;

		return result;
	}

auf der anderen Seite gibts immernoch RetroWeaver mit dem fuer Java 5 entwickelte Anwendung auf Java 1.4 lauffaehig machen kann...
http://retroweaver.sourceforge.net/

Gruss Tom
 
ja, ich habs jetzt auch so gelöst!

Retroweaver kannte ich bisher noch nicht. Danke für den Tipp, muss ich mir unbedingt mal angucken!

gruss
ben
 
Zurück