What does it mean to say a type is “boxed”?

后端 未结 6 1384
刺人心
刺人心 2020-12-11 00:15

I have heard of types being referred to as \"boxed\" in some languages.

In Java, I have heard of \"autoboxing\". What is this? Is it having wrapper classes for a ty

6条回答
  •  萌比男神i
    2020-12-11 00:57

    Yes, boxing means taking a value type and wrapping it in a reference type. Since java introduced autoboxing you can do:

    void foo(Object bar) {}
    //...
        foo(1);
    

    And java will automatically turn the int 1 into an Integer. In previous versions you'd have to do:

    foo(new Integer(1));
    

    Autoboxing is most useful in java when working with generics, since you can't use primitives with generics, so to store ints in a list, you'd have to make a List and put the ints into the list boxed.

提交回复
热议问题