What is the difference between an int and an Integer in Java and C#?

前端 未结 26 1739
生来不讨喜
生来不讨喜 2020-11-22 12:00

I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an i

26条回答
  •  执笔经年
    2020-11-22 12:38

    01. Integer can be null. But int cannot be null.

    Integer value1 = null; //OK
    
    int value2 = null      //Error
    

    02. Only can pass Wrapper Classes type values to any collection class.

    (Wrapper Classes - Boolean,Character,Byte,Short,Integer,Long,Float,Double)

    List element = new ArrayList<>();
    int valueInt = 10;
    Integer  valueInteger = new Integer(value);
    element.add(valueInteger);
    

    But normally we add primitive values to collection class? Is point 02 correct?

    List element = new ArrayList<>();
    element.add(5);
    

    Yes 02 is correct, beacouse autoboxing.

    Autoboxing is the automatic conversion that the java compiler makes between the primitive type and their corresponding wrapper class.

    Then 5 convert as Integer value by autoboxing.

提交回复
热议问题