简体   繁体   English

如何通过哈希随机化(在Java中)?

[英]How to randomize by hash (in Java)?

I have ArrayList of Strings. 我有字符串的ArrayList。 I need to randomize it by "hash number". 我需要通过“哈希数”将其随机化。 Example: 例:

ArrayList: "Word", "Simple", "Another", "Demo" hash: 1234567 ArrayList:“ Word”,“ Simple”,“ Another”,“ Demo”哈希: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" 其他哈希值:542345我想收到说:“单词”,“另一个”,“演示”,“简单”

But the requirements is that that when I always sort by this hash the randomizing order will always be THE SAME for that HASH. 但要求是,当我始终按此哈希排序时,随机顺序将始终与该HASH相同。

Any suggestions? 有什么建议么? Adviscs? 咨询?

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. 当使用相同的哈希值作为Random对象的种子时,混洗顺序应相同。

使用“哈希”(无论什么意思)作为随机数生成器的种子?

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. 因此,如果您确实需要使用哈希,则可以遍历ArrayList,总结所有生成的哈希值并保存。

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. 现在,当您需要验证哈希值是否相同时,再次遍历新的数组列表,生成hashcode(),对其进行汇总并检查。

But it's an overkill. 但这太过分了。 You can simply use shuffle() as suggested by Bill. 您可以按照Bill的建议简单地使用shuffle()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM