I have a program which only needs one random number, the random number can be insecure, so I am trying to use the hash code of args as random number because it does not require any additional import statements:
public class Test{
public static void main(String[] args){
int r=args.hashCode();
System.out.println(r);
}
}
but after I run 20 times, I found the hash code of args looks not so random:
1265744841
745503977
745503977
400535505
1265744841
745503977
745503977
745503977
1265744841
1265744841
745503977
1265744841
1586482837
1265744841
56264551
745503977
745503977
745503977
400535505
1265744841
It looks some values appeared repeatedly, and I try to reboot machine and run the program 20 times again, some values still appear repeatedly, and some values are even the same as values before reboot:
745503977
745503977
745503977
745503977
745503977
400535505
745503977
745503977
745503977
745503977
745503977
745503977
745503977
1265744841
745503977
745503977
745503977
745503977
745503977
1265744841
and even I added some values in args (e.g.:java Test abc), similar sets of values still appear, what is the reason?
You're calling hashCode()
on an array. Arrays don't override hashCode()
, equals()
or toString()
- so you're getting a result which doesn't depend on the content of the array at all, and probably depends on where it happens to be in memory. If you wanted a hash code depending on the values within the array, you could call Arrays.hashCode(args)
- but then you'd always get the same result for the same input, which isn't your intention.
Now, as for your purpose:
I have a program which only needs one random number, the random number can be insecure, so I am trying to use the hash code of args as random number because it does not require any additional import statements
That's a terrible, terrible reason to decide to use something... and hash codes should never be used as random number generators.
If you really, really don't want to add an import statement (and why not?) just use Random
explicitly:
int x = new java.util.Random().nextInt(100); // Or whatever
See more on this question at Stackoverflow