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

后端 未结 9 1268
猫巷女王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 22:03

    It exists so that you can write code like

    List is = new ArrayList();
    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 ==).

提交回复
热议问题