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

后端 未结 6 1386
刺人心
刺人心 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条回答
  •  遥遥无期
    2020-12-11 00:43

    More specific information for Java:

    Autoboxing allows java to automatically convert things like boolean and int to their Object versions Boolean and Integer automatically in most cases. It also allows the reverse to happen.

    For example:

    int a = 3; // no boxing is happening
    Integer b = 3;  // newer versions of java automatically convert the int 3 to Integer 3
    int c = b;  // these same versions also automatically convert Integer 3 to int 3
    

    Older versions of java that do not have autoboxing will require this code to do the same thing:

    int a = 3;  // works the same
    Integer b = new Integer(3);  //must set up a Integer object manually
    int c = b.intValue(); //must change Integer object to a primitive
    

    However, there are some scenarios where you still have to do things manually. For example, imagine you have a class with two methods like so:

    assertEquals(int a, int b);
    assertEquals(Object a, Object b)
    

    Now, if you try to do this:

    Integer a = 3;
    int b = 3;
    assertEquals(a, b);  // this will not compile
    

    The reason this doesn't work is because it cannot figure out whether it should unbox a to an int or box b to an Integer. Therefore it is ambiguous which method signature should be called. To fix this you can do one of these:

    assertEquals((int) a, b);
    assertEquals(a, (Integer) b);
    

提交回复
热议问题