1

I have ArrayList of Strings. I need to randomize it by "hash number". Example:

ArrayList: "Word", "Simple", "Another", "Demo" hash: 1234567

As a result of randomizing I want to receive say: "Simple", "Word", "Demo", "Another"

with other hash: 542345 I want to receive say: "Word", "Another", "Demo", "Simple"

But the requirements is that that when I always sort by this hash the randomizing order will always be THE SAME for that HASH.

Any suggestions? Adviscs?

1
  • why is consistent hashing marked as a tag? It's a diff algo for DHT routing. Commented Nov 3, 2010 at 2:03

3 Answers 3

5

You can shuffle a List using a Random object that you initialize with the hash.

Collections.shuffle( myList, new Random(12345) ); 

When the same hash is used to seed the Random object, the shuffle order should turn out the same.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks; I couldn't find any doc confirming that shuffle by same Random object will return the same collection. Can you please point me to one? Thanks!
@alexeypro: It can be inferred from the docs of the two methods involved Collections.shuffle and the Random(long) constructor. Passing the same seed to the Random constructor will insure that the RNG is in the same initial state each time shuffle is called, resulting in the same ordering of the list.
1

Use the "hash" (whatever than means) as a seed to the random number generator?

Comments

0

You can do this:

value1 = "hello" --> value1.hashCode() = 99162322 value2 = "hello" --> value2.hashCode() = 99162322 

So, if you 'really' need to use a Hash, then you can iterate through the ArrayList, sum up all the hash values generated and save it.

Now, when you need to verify that the hash is same or not, again iterate through the new arraylist, generate the hashcode(), sum it up and check.

But it's an overkill. You can simply use shuffle() as suggested by Bill.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.