mrQWERTY
mrQWERTY

Reputation: 4149

Fastest way to generate a hash key for an int[] array?

For instance int[] array = {1,2,3,4,5,6,7,8,9};

I want to convert this into int a = 123456789;

I am intending to use this as hash key.

My idea is to convert the array into a string using Arrays.toStringand then convert it back to an integer. But I think that is not a good solution. Any thoughts?

Upvotes: 2

Views: 1650

Answers (3)

Mad Angle
Mad Angle

Reputation: 2330

Arrays.hashCode(int[]) would be helpful..

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201437

For a real hash I would use Arrays.hashCode(int[]), but your requested function can be done with one line -

int a = Integer.parseInt(Arrays.toString(array)
    .replaceAll("\\[|\\]|,\\ ", ""));
System.out.println(a);

Output is

123456789

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361605

Why reinvent the wheel? Use Arrays.hashCode(int[]) to get a hash code based on the array contents.

Upvotes: 8

Related Questions