原始类型包装器

Primitive Type Wrappers

我目前正在阅读名为 Java 完整参考的书。在第 18 章中,有对 Primitive Type Wrappers 的介绍。

As mentioned in Part I of this book, Java uses primitive types, such as int and char, for performance reasons. These data types are not part of the object hierarchy. They are passed by value to methods and cannot be directly passed by reference. Also, there is no way for two methods to refer to the same instance of an int At times, you will need to create an object representation for one of these primitive types. For example, there are collection classes discussed in Chapter 19 that deal only with objects; to store a primitive type in one of these classes, you need to wrap the primitive type in a class.

作者在粗体字中的实际含义是什么? 两个方法无法引用 int 的同一个实例。 如果有人用一个例子来解释这一行,那就太好了:) 提前谢谢你。

我对粗线的考虑可能是错误的,正如社区用户在评论中提到的那样。但是,AFAIK,它试图说如果将原始类型变量或原始类型的包装器传递给两个方法,那么这两个方法都有不同的副本。我已经实施了一个示例来帮助您解决这个问题。

您可以尝试 运行 它并查看所有情况下的输出。在传递 int 或 Integer 的情况下,值的变化不会反映在另一个方法中。

请原谅我的驼峰式外壳。

public class TestPrimitive
{

    public static void main(String[] args)
    {
        int i = 15;
        Integer j = 20;
        StringBuffer str = new StringBuffer("Hello");
        XYZ obj = new XYZ(10);
        printIWithAddition(i);
        printIWithoutAddition(i);
        IntegerWrapperWithChange(j);
        IntegerWrapperWithoutChange(j);
        StringBufferWithChange(str);
        StringBufferWithoutChange(str);
        XYZWithChange(obj);
        XYZWithoutChange(obj);
    }

    private static void printIWithAddition(int i) {
        i++;
        System.out.println(i);
    }

    private static void printIWithoutAddition(int i) {
        System.out.println(i);
    }

    private static void IntegerWrapperWithChange(Integer j) {
        j++;
        System.out.println(j);
    }

    private static void IntegerWrapperWithoutChange(Integer j) {
        System.out.println(j);
    }

    private static void StringBufferWithChange(StringBuffer str) {
        System.out.println(str.append(" World"));
    }

    private static void StringBufferWithoutChange(StringBuffer str) {
        System.out.println(str);
    }

    private static void XYZWithChange(XYZ obj) {
        obj.a = 20;
        System.out.println(obj);
    }

    private static void XYZWithoutChange(XYZ obj) {
        System.out.println(obj);
    }
}

class XYZ {

    int a;

    public int getA()
    {
        return a;
    }

    public void setA(int a)
    {
        this.a = a;
    }

    public XYZ(int a)
    {
        this.a = a;
    }

    @Override public String toString()
    {
        return "XYZ{" + "a=" + a + '}';
    }
}