Javadoc说“
“将此ArrayList实例的容量调整为列表的当前大小”
以下是用于理解功能的测试程序,
ArrayList<Integer> arraylist = new ArrayList<Integer>(50);
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);
arraylist.add(4);
arraylist.add(5);
arraylist.add(6);
arraylist.add(7);
arraylist.add(1);
arraylist.add(1);
arraylist.add(1);
System.out.println(arraylist);
arraylist.trimToSize();
System.out.println(arraylist);
但两种情况下的输出都相同。
[1,2,3,4,5,6,7,1,1,1]
任何人都可以帮我理解如何使用此方法缩小arraylist大小?
答案 0 :(得分:1)
Use the source,卢克!
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}