Comparator<Integer> naturalOrder = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 < o2 ? -1 : (o1 == o2 ? 0 : 1); } }; System.out.println(naturalOrder.compare(new Integer(10), new Integer(10))); //The result is 1 Reason: The calculation of o1<o2 on the expression will cause the Integer instance to be unpacked automatically, and then the expression o1==o2 is executed. It performs identity comparison on two object references. If o1 and o2 refer to Integer instances that represent the same int value, the result returns false. It is almost always wrong to apply the==operator to the boxing type
static Integer i; public static void main(String[] args) { if(i==42) System.out.println("Unbelievable"); } //Result java.lang.NullPointerException Reason: i is an Integer, not an int, and all initial values are null When basic types and packing types are mixed in one operation, the packing type will be unpacked automatically. If the null object reference is unpacked automatically, you will get a NullPointerException
Long sum=0L; long startTime=new Date().getTime(); for(long i=0; i<Integer.MAX_VALUE;i++){ sum+=i; } long endTime=new Date().getTime(); System. out. println ("Total time:"+(endTime startTime)); //Total time: 29079 Change to long sum=0L; //Total time: 6724 Cause: Variables are repeatedly packed and unpacked, resulting in significant performance degradation