In the program I was working on, I ran into a data storage problem, especially related to ArrayLists. This is not the code I tested, but it gives an example of what I mean.
public class test { public static void test() { ArrayList<Integer> bob = new ArrayList<Integer>(); bob.add(129); bob.add(129); System.out.println(bob.get(0) == 129 ); System.out.println(bob.get(1) == 129 ); System.out.println(bob.get(0) == bob.get(1) ); } }
If you run it, you will get true, true and false. The code recognizes that both values are 129, but for some reason returns false when it tries to see if they are equal to each other. However, if you change the value to 127, it will return true, true, and true. Repeating this several times for different values, you will see that the minimum value to get true, true and true is -128, and the maximum value is 127. This is an interval for a byte, which makes me suspect that the == operation is using a byte in this case .
Interestingly, if you change the code so that it reads
public class test { public static void test() { ArrayList<Integer> bob = new ArrayList<Integer>(); bob.add(129); bob.add(129); int a = bob.get(0); int b = bob.get(1); System.out.println(a == 129 ); System.out.println(b == 129 ); System.out.println(a == b ); } }
it works as intended. true, true and true. Why does saving values as int before comparing change the result? This is because if they are not saved, the comparison will use the default bytes for comparison ==
source share