ArrayListresize
我有一个ArrayList对象,我知道它的确切大小。 有没有办法指定ArrayList不应该扩展其容量?
List list = null; int size = getSize(); // gets the exact number of elements I want list = new ArrayList (size); for (int i = 0; i < size; i++) { list.add("String num: " + i); }
我不希望ArrayList重新resize,因为这需要我想避免浪费的时间。
list = new ArrayList (size);
这将创建以’size’作为初始容量的arraylist。 只要您不添加超过“大小”的元素,就不会resize。
另外请确保您的申请需要时间。 除非您已对此进行了分析并将其识别为问题,否则您将无法通过随机优化代码获得更多收益。
如果您没有添加超出其容量的元素,则ArrayList
将不会resize。 你已经创建了具有合适容量的列表,所以应该没问题。
如果你试图超过原始容量,你可以创建一个抛出exception的列表,但是不清楚为什么这对你有用。
如果您知道确切的大小,并且将来不会扩展,那么为什么不使用String数组。
String[] strArray=new String[size];
您可以做的限制ArrayList
方法是覆盖ensureCapacity(int minCapacity)
方法,如下例所示:
public static class MyArrayList extends ArrayList { @Override public void ensureCapacity(int minCapacity) { if (minCapacity > 10) { throw new IllegalArgumentException(); } super.ensureCapacity(minCapacity); } }
可以使用以下代码进行小测试:
public static void main(String[] args) { MyArrayList items = new MyArrayList (); for (int i = 0; i < 15; i++) { try { items.add("itm " + i); System.out.println("succeeded to insert " + i); } catch (IllegalArgumentException e) { System.out.println("not able to insert " + i); } } System.out.println("items are: " + items); }
这将打印:
succeeded to insert 0 succeeded to insert 1 succeeded to insert 2 succeeded to insert 3 succeeded to insert 4 succeeded to insert 5 succeeded to insert 6 succeeded to insert 7 succeeded to insert 8 succeeded to insert 9 not able to insert 10 not able to insert 11 not able to insert 12 not able to insert 13 not able to insert 14 items are: [itm 0, itm 1, itm 2, itm 3, itm 4, itm 5, itm 6, itm 7, itm 8, itm 9]