what is difference between integer a = 5 and new Integer(5)?

前端 未结 5 887
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 22:33

if i write below code(in java):

Integer a =new Integer(5);
Integer b=new Integer(5);
if(a==b){
  System.out.println(\"In ==\");
}
if(a.equals(b)){
 System.o         


        
5条回答
  •  余生分开走
    2020-12-05 22:46

    In Java, you should never use the new Integer, even though it is valid syntax it is not the best way to declare integers as you have found out. Use instead Integer.valueOf(int) This has multiple advantages.

    You are not creating extra objects needlessly. Whenever you use the new operator you are forcing the vm to create a new object which is not needed in most cases. valueOf(int) will return a cached copy. Since Integer objects are immutable this works great. This means that you can use == though in practice you should use a null safe compare like in Apache ObjectUtils

    The == operator tests for equality. References are only equal when they refer to the same object in memory. equals method ensures 2 object instances are 'equivalent' to each other.

    Integer a = new Integer(5);
    Integer b = a;
    
    a == b; // true!
    a.equals(b); // true
    b = new Integer(5);
    a == b; // false
    a.equals(b); // true
    

    Primitives are equal whenever their value is the same.

    int a = 5; int b = a;
    a == b;  // true!
    

提交回复
热议问题