Im working on a small Project and have encountered a problem(?) I cant really explain. This is my code:
====Main=====
Beacon b1 = new Beacon("192.168.0.12", 72.0);
Beacon b4 = new Beacon("192.168.0.13", 72.0);
Beacon b2 = new Beacon("192.168.0.24", 84.0);
Beacon b3 = new Beacon("192.168.0.5", 64.0);
ArrayList<Beacon> alBeacons = new ArrayList();
alBeacons.add(b4);
alBeacons.add(b2);
alBeacons.add(b1);
alBeacons.add(b3);
Room room = new Room("Testroom", alBeacons);
====Beacon====
public class Beacon {
String sIP;
private int ID = 0;
private Double RSSi;
public Beacon(String sIP, double RSSi){
this.sIP = sIP;
this.RSSi = RSSi;
setID();
}
private void setID(){
String sTemp[] = sIP.split("\\.");
this.ID = Integer.parseInt(sTemp[sTemp.length-1]);
}
public String getsID(){
return String.valueOf(ID);
}
public int getID(){
return ID;
}
}
====Room====
public Room(String sName, ArrayList<Beacon> alBeacons){
System.out.println("Unsorted: " + alBeacons.hashCode());
for(Beacon b: alBeacons){
System.out.println(b.getID());
}
alBeacons.sort(new Comparator<Beacon>() {
@Override
public int compare(Beacon o1, Beacon o2) {
return o1.getID() - o2.getID();
}
});
System.out.println("Sorted: " + alBeacons.hashCode());
for(Beacon b: alBeacons){
System.out.println(b.getID());
}
}
Now my Problem I have is that in the unsorted state, no matter how the Beacons have been inserted into the ArrayList, I always get the same HashCode(), 1498918675. As soon as I sort them, I get a different HashCode, which makes sense. But the Problem now is that, depending on how the ArrayList was sorted in the first place, I get a different HashCode after sorting it. Is this inherent to .sort(), or is my fix for real number sorting breaking it?
EDIT: Here are some output examples:
Unsorted: 1498918675
13
24
12
5
Sorted: 341854239
5
12
13
24
Unsorted: 1498918675
24
5
12
13
Sorted: 638040239
5
12
13
24
Unsorted: 1498918675
12
5
24
13
Sorted: 1060992495
5
12
13
24