Java 8中,ArrayList的默认容量为0
2020-08-20 本文已影响0人
rainbowz
答案是节省内存消耗。在实时Java应用程序中创建了数百万个数组列表对象。默认大小为10个对象意味着我们在创建时为底层数组分配10个指针(40或80个字节),并用空值填充它们。空数组(填充空值)占用大量内存。
延迟初始化会推迟此内存消耗,直到您实际使用数组列表为止。
请参阅以下代码以获取帮助。
ArrayList al = new ArrayList(); //Size: 0, Capacity: 0
ArrayList al = new ArrayList(5); //Size: 0, Capacity: 5
ArrayList al = new ArrayList(new ArrayList(5)); //Size: 0, Capacity: 0
al.add( "shailesh" ); //Size: 1, Capacity: 10
public static void main( String[] args )
throws Exception
{
ArrayList al = new ArrayList();
getCapacity( al );
al.add( "shailesh" );
getCapacity( al );
}
static void getCapacity( ArrayList<?> l )
throws Exception
{
Field dataField = ArrayList.class.getDeclaredField( "elementData" );
dataField.setAccessible( true );
System.out.format( "Size: %2d, Capacity: %2d%n", l.size(), ( (Object[]) dataField.get( l ) ).length );
}
Response: -
Size: 0, Capacity: 0
Size: 1, Capacity: 10