开发者

How to delete contents of Map?

开发者 https://www.devze.com 2023-03-24 07:54 出处:网络
So I had built a program, and everything seemed to be going fine until I got to the debugging stages. And one of the开发者_JAVA技巧 big problems I found was that the LinkedHashMap I had been using was

So I had built a program, and everything seemed to be going fine until I got to the debugging stages. And one of the开发者_JAVA技巧 big problems I found was that the LinkedHashMap I had been using was not actually deleting it's previous contents when I called map.clear() at the end of the loop. So I was wondering if anyone knew or could show me a good iterative way to delete the contents of a map?


This perfectly works in Open JDK 1.6. And if you look into the source for LinkedHashMap, there's simply no chance this cannot work.

public static void main(String[] args) {
    LinkedHashMap<String, String> test = new LinkedHashMap<String, String>();
    test.put("a", "1");
    test.put("b", "2");
    test.put("c", "3");
    test.put("d", "4");

    System.err.println(test);
    test.clear();
    System.err.println(test);
}

EDIT: Does this describe your problem?


The Map interface declares clear() as an optional operation. However, your tag says you're using LinkedHashMap and the Javadocs do say the map should be empty when the call returns. Can you provide a code sample demonstrating that you can still retrieve an element by some key even after calling clear()?

EDIT #1: It occurs to me that you may mean the objects themselves are not immediately garbage collected after the mappings are removed from your Map; that wouldn't surprise me at all. Clearing the entries in the map doesn't mean the objects themselves have to be garbage collected or finalized right when that method completes. Can you clarify what you expect, please?

EDIT #2 I wrote the following test case:

public static void main(String args[]) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("one", 1);
    map.put("two", 2);
    map.put("three", 3);
    System.out.println(map);
    map.clear();
    System.out.println(map);
}

And observed the following output:

{one=1, two=2, three=3}
{}

Can you please provide a code sample that demonstrates exactly what you're doing, that differs from this?


Objects are only deleted when they're removed by the garbage collector (whose schedule is implementation-dependent). So the only thing you can really do is make sure that no references to those Objects exist in your application. If there are, then they won't be garbage collected.

You can try and poke the VM into garbage collecting by calling System.gc();.

0

精彩评论

暂无评论...
验证码 换一张
取 消