清除类型对象的数据

时间:2013-05-05 11:41:44

标签: java object

我使用类型对象,我用循环中的数据填充它,最后我想清除里面的数据,我没有看到任何清除它的选项(使用。+ CTRL SPACE),我不想要为它创建新实例,因为我只想创建一次对象类型,是否有解决方法来清除它?

我想对specObject执行以下一次,即创建实例类型列表或对象,而不是我有循环,我填充此对象内的数据,当我完成并想在specObject中创建新实例我想清除之前,我应该怎么做?

List<Object> itemObject = null;
        Object specObject = null;

        // Check instance type whether is list or specific object instance
        if (multiplicity.equals(MULTI_N)) {
            itemObject = new ArrayList<Object>();
            return itemObject;
        } else if (multiplicity.equals(MULTI_1)) {
            return specObject;
        } else {
            return specObject;
        }

1 个答案:

答案 0 :(得分:1)

您可以在clear对象上调用List方法。这将删除所有元素,而无需创建新实例。文档是here

请注意对象引用

  

当我完成并希望在specObject中创建新实例时我想先清除它,我应该怎么做?

假设你有一个清单:

ArrayList<String> strings = new ArrayList<String>();

如果您将一些字符串对象添加到此列表中:

strings.add("Hello");
strings.add("There");
strings.add("StackOverflow");

然后取消strings对象。

strings = null;

您是否已有效删除了列表中的所有元素?为什么?那么当你声明ArrayList<String> strings;时,你就不会创建一个新对象。您正在创建对象的新引用(指针)。为了说明这一点:

String s = "Hello";
String s2 = s; // s2 points to the same object that s points to.
String s3 = "Another String"; // S3 points to a different object.

此规则的一个例外是,如果您声明:

String s = "Hello";
String s2 = "Hello"; // s2 will point to the same object as s.

当任何对象未被指向时,它将被垃圾收集器删除。如此有效,如果您声明:

strings = null;

您要删除添加到的所有String子对象。