开发者

Adding a single element to an ArrayList adds another 11 null elements?

I'm populating an ArrayList 'pts' of Points.

To me this seems pretty straightforward but after this runs there are null elements in the arraylist.

for(int i =0; i< currentt.getPointCount();i++){
   File pXml = new File(tourFolderPath + "point_" + (i+1)开发者_C百科 +".xml");
   if (pXml.exists()){
      pt = (Point)MXP.createObject(pXml, 2);
   }
   pts.add(pt);
}

After inspecting in the debugger it seems that the very first time the line "pts.add(pt);" is run it adds one legitimate point element. However, it also adds 10 other null elements.

Any ideas?


An ArrayList contains an initial capacity of 10.


I just ran a simple program in my debugger and you will see what everyone is talking about. Initializing it creates 10 null entries. These null entries are not accessible. This is why size is shown as 0. If you add an element, the size will change to 1.

Adding a single element to an ArrayList adds another 11 null elements?


If you look at the ArrayList through the debugger, you are probably seeing it's backing array, and this array is as long as the ArrayLists capacity.

The backing array intentionally has more slots than the number of currently inserted elements. This enables faster insertion, since it doesn't need to reallocate the array for every element it is asked to store.

If you look at the size attribute of the ArrayList, you'll probably see the correct number of elements.


it looks like pXml.exists() is true for first time and false for other times.

You add pt anyway even if pXml doesn't exist.

Please show more code.


When you make new ArrayList(); it creates one with initial capacity equal to 10. You can change this behaviour by passing an int to the constructor. Read more here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜