Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);

后端 未结 9 1131
猫巷女王i
猫巷女王i 2020-12-01 21:04

Autoboxing seems to come down to the fact that I can write:

Integer i = 0; 

instead of:

Integer i = new Integer(0);


        
相关标签:
9条回答
  • 2020-12-01 21:53

    Makes for more readable and neater code. Especially if you're doing operations (Since Java doesn't have operator overloading).

    0 讨论(0)
  • 2020-12-01 21:54

    BTW

    Integer i = 0;
    

    is equivalent to

    Integer i = Integer.valueOf(0);
    

    The distinction is that valueOf() does not create a new object for values between -128 and 127 (Apparently this will be tunable if Java 6u14)

    0 讨论(0)
  • 2020-12-01 22:03

    It exists so that you can write code like

    List<Integer> is = new ArrayList<Integer>();
    is.add(1); // auto-boxing
    is.add(2);
    is.add(3);
    
    int sum = 0;
    for (int i : is)  // auto-unboxing
    {
        sum += i;
    }
    

    For single integers you should by default use the type int, not Integer. Integer is mostly for use in collections.

    Beware that a Long is different from the same value as an Integer (using equals()), but as a long it is equal to an int (using ==).

    0 讨论(0)
提交回复
热议问题