开发者

can not understand with null and clear statement in this example

Sorry for my poor english, I test the List object with clear method and to assign null value

here is code

public class TestList {
private List<String> list;
private List<List<String>> mainList;

public TestList(){
    list = new ArrayList<String>();
    mainList = new ArrayList<List<String>>();
}
public static void main(String arg[]){
    String[] mylist = {"sunday","monda","tuesday","wednesday","thurday","friday","saturday"};

    TestList tl1 = new TestList();

    for(String s : mylist)
        tl1.list.add(s);


    tl1.mainList.add(tl1.list);

    //tl1.list.clear(); // here if clear then not getting the list

    tl1.list = null; ///// but here to assign null still getting list

    System.out.println("after clear");
    System.out.println();
    for(List<String> list : tl1.mainList){
        for(String s : list){
            System.out.println(s);
    开发者_开发知识库    }
    }

}
 }

so my question is when I clear the tl1.list using tl1.list.clear(); and then print the value it's clear but when I assing null to this tl1.list then it will print the value how?


tl1.list.clear() clears the list list which was added to mainList as well. As Java is object-oriented list and mainList.get(0) reference exactly the same object. If you set tl1.list to null, you only dereference the object, it is still available in mainList.

I'm not sure if I understood your question, but I guess this is what you asked...


Assigning a null to any collection does not mean that the elements associated with it will be removed. It only means that you no longer require that object anymore. Now it is up to garbage collector who then dereference this object. If there are lots of statements between the null assignment and print statements this may cause a problem since GC may get time to dereference it.
I hope my answer will help you understand this.


It's not clear what you are asking, maybe you think clear() deletes the object - that's not true, it makes the list empty.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜