java中的意义arraylist参数 [英] Significance arraylist argument in java

查看:102
本文介绍了java中的意义arraylist参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>List<Integer> l=new ArrayList<>();
       l.add(1);
       l.add(2);
       l.add(3);
       l.add(4);
       System.out.println("Element at 0th index: "+l.get(0));
       Iterator i=l.iterator();
        while(i.hasNext())
        {
            Integer obj=(Integer)(i.next());
            int o=obj;
            System.out.println(o);
        }





输出:



ouput:

Element at 0th index: 1
1
2
3
4





我尝试了什么:





What I have tried:

<pre lang="java"><pre>List<Integer> l=new ArrayList<>();



将以上行更改为以下


Upon changing the above line to the following

<pre><pre lang="java"><pre>List<Integer> l=new ArrayList<>(2);



获得相同的输出。任何人都可以解释使用ArrayList中传递的参数作为ArrayList(2)吗?


the same output is obtained. Could anyone explain the use of argument passed in ArrayList as ArrayList(2) ?

推荐答案

它是; ArrayList的初始容量:ArrayList(Java Platform SE 7) [ ^ ] - 如果未指定,则以容量为10.当您将其指定为2时,它仅分配两个要素。



这是为了提高效率 - 如果您知道要使用多少元素,那么您可以从容量开始并保存不断的重新分配,直到达到它为止。

见这里:列表与LT; T> - 它是否真的像您想象的那样高效? [ ^ ] - 它基于C#,但Java ArrrayList完全相同,原因相同。
It;s the initial capacity of the ArrayList: ArrayList (Java Platform SE 7 )[^] - if it isn't specified then it starts with a capacity of 10. When you specify it as 2 it allocates just two elements to start with.

It's for efficiency - if you know how many elements you are going to use, then you can start with that as the capacity and save the constant reallocation until you reach it.
See here: List<T> - Is it really as efficient as you probably think?[^] - it's C# based but the Java ArrrayList does exactly the same thing, for the same reasons.


这篇关于java中的意义arraylist参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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