Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - does reallocating a List using subList hold a reference to previously allocated memory?

Tags:

java

I inherited some java code which keeps a list of items to be displayed in a GUI table. The list has a size constraint so that only the most recent 100 items are displayed. When the list size reaches the limit, the code reallocates a new list, keeping the most recent 50 items via subList().

I have a concern that when this occurs, a reference may still be kept to the previously allocated list, keeping it from getting garbage collected. Can someone tell me if this is really an issue or not?

private List<myclass> theList= new LinkedList<myclass>();

public int addToList( myclass newitem) {

  theList.add(0, newitem);

  if (theList.size() > 100) {

    theList = new LinkedList<myclass>(theList.subList(0, 50));

  }
}
like image 803
user3866982 Avatar asked Jul 23 '14 03:07

user3866982


1 Answers

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

http://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList(int,%20int)

subList() returns a view of the original list so it does remain used. However, once you get to new LinkedList<myclass>(theList.subList(0, 50));, it will make a shallow copy and you will lose the reference to the old list.

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)

like image 200
Xinzz Avatar answered Oct 31 '22 18:10

Xinzz