java - Collections.sort Hashcodes -
why below code printing different hashcodes on calling collections sort method kindly let me know why behaviour?
list<integer> list = new arraylist<>(); (int = 0; < 10; i++) { list.add((int) (math.random() *100)); } system.out.println("before list =" + list); system.out.println("object hashcode-1 =" + list.hashcode()); collections.sort(list); system.out.println("in >>> object hashcode-1 =" + list.hashcode()); collections.sort(list,new comparator<integer>() { @override public int compare(integer o1, integer o2) { return (o1.intvalue() > o2.intvalue() ?-1:1); } }); system.out.println("object hashcode-2 =" + list.hashcode()); system.out.println("after list =" + list); collections.sort(list,collections.reverseorder()); system.out.println("object hashcode-3 =" + list.hashcode()); system.out.println("reverse order list =" + list);
the output is:
before list =[58, 12, 38, 36, 56, 78, 65, 70, 51, 63] object hashcode-1 =545500024 in >>> object hashcode-1 =975071634 object hashcode-2 =1492547664 after list =[78, 70, 65, 63, 58, 56, 51, 38, 36, 12] object hashcode-3 =1492547664 reverse order list =[78, 70, 65, 63, 58, 56, 51, 38, 36, 12]
regards
a list ordered collection. means list [1, 2]
not equal list [2, 1]
nor should hashcode() same (ideally)
when sort collection change it's order , it's hashcode. note not guarenteed types. e.g. long of formula ((x + y) & 0xffffffff) + y << 32)
have same hashcode same value of x
. means have list of long
each long has same hashcode , list of these numbers have same hashcode regardless of order.
list<long> l1 = arrays.aslist(-1l, 0l, (1l << 32) + 1, (2l << 32) + 2); list<long> l2 = arrays.aslist((2l << 32) + 2, (1l << 32) + 1, 0l, -1l); system.out.println(l1.hashcode()); system.out.println(l2.hashcode());
as long use hashcode of 0, order doesn't change hashcode.
923521 923521
Comments
Post a Comment