【问题标题】:Why object instantiation is not needed in some cases such as this?为什么在某些情况下不需要对象实例化?
【发布时间】:2017-02-14 11:31:39
【问题描述】:

为什么有时我们不必创建对象,只需将其分配给方法等?以follow为例。

List<String> list1 = new ArrayList<>();
List<String> list2 = Collections.synchronizedList(list1);

这是否意味着list2 被分配了一个ArrayList 对象?在这种情况下,内存分配会发生什么?谢谢!

【问题讨论】:

    标签: java object memory-management reference instantiation


    【解决方案1】:

    List2 被分配了列表的一些实现。在确切的情况下,它是SynchronizedRandomAccessList 对象或SynchronizedList 对象,但不是ArrayList

    Here是源码:

    public static <T> List<T> synchronizedList(List<T> list) {
            return (list instanceof RandomAccess ?
                    new SynchronizedRandomAccessList<>(list) :
                    new SynchronizedList<>(list));
    }
    

    静态方法synchronizedList() 在这种情况下只是一个助手。 java 中的对象(不是原始值)用于传递对内存位置的引用。所以synchronizedList() 返回一个对new SynchronizedList() 对象的内存引用,通过调用它,您将该内存位置分配给您的list2 对象。

    【讨论】:

      【解决方案2】:

      始终需要对象实例化。在 Java 中有两个内存区域:线程栈和堆。

      • 基元(即不是对象的变量),如 boolean、byte、short、char、int、long、float、double,存储在线程堆栈中
      • 使用new 关键字创建的对象在堆中分配

      在您的情况下,在方法 Collections.synchronizedList 中实例化的 List 对象将在堆中分配,对该列表的引用将分配给局部变量 list2

      【讨论】:

        猜你喜欢
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-29
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 2022-07-22
        相关资源
        最近更新 更多