arraylist的remove()方法导致arraylist的大小缩小 [英] remove() method of arraylist is leading to shrinking size of arraylist

查看:323
本文介绍了arraylist的remove()方法导致arraylist的大小缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到,当我们从ArrayList中删除Object时,它的大小不会减小.

I have read that when we remove an Object from ArrayList, its size doesn't decrease.

我尝试了以下代码进行测试,但发现尺寸减小了.有人可以纠正或向我解释吗?

I tried the below code to test this, but found that size is decreased. Could anyone correct or explain this to me?

package collections;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {  
public static void main(String[] args) {  
    //Creating list of Books  
    List<Book> list=new ArrayList<Book>();  
    //Creating Books  
    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  
    Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);  
    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  
    //Adding Books to list  
    list.clear();
    list.add(b1);  
    list.add(b2);  
    list.add(b3); 
    list.contains(b3);
    int size= list.size();
    System.out.println(size);
    list.remove(b3);
    int size1= list.size();
    System.out.println(size1);      
}  
}  

推荐答案

您可能已经读到ArrayList所使用的 backing array 的大小并没有减少,这是事实.如果将100个元素放在ArrayList中,它将具有至少100个大小的后备数组.即使在remove()元素之后,该数组的大小也保持不变.要释放该内存,可以使用trimToSize()方法:

You probably read that the size of the backing array used by the ArrayList doesn't decrease, which is true. If you put 100 elements in an ArrayList, it will have a backing array of at least 100 in size. Even after you remove() elements, the size of that array stays the same. To free up that memory, the trimToSize() method is available:

public void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

来自 https://docs .oracle.com/javase/7/docs/api/java/util/ArrayList.html#trimToSize()

这篇关于arraylist的remove()方法导致arraylist的大小缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆