0

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) +".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?

1
  • How is the array list created? Can you supply a bit more source? Commented Apr 15, 2011 at 12:07

5 Answers 5

6

An ArrayList contains an initial capacity of 10.

Sign up to request clarification or add additional context in comments.

2 Comments

The debugger will report lots of nulls, but they're just being saved in case you need to add more elements later. They're not accessible through the ArrayList's interface.
Ah quite right! Ok, the problem was cropping up later on when I was cycling through the list using an Iterator. Using the pointItr.hasNext() returns true for the null elements, thus causing all sorts of nastiness later on. It's clear that I need to get rid of those null elements before using the iterator.
2

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.
Screenshot of ArrayList in debugger, indicating the size as 0

Comments

2

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.

Comments

1

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.

1 Comment

You're absolutely right about that - good spot. I still have the other problem though
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.