ArrayList<String> doesn't set minimum capacity
private static ArrayList<String> places(ArrayList<Road> roads) {
ArrayList<String> places = new ArrayLis开发者_如何学编程t<String>(10); // tried setting minimum capacity
places.ensureCapacity(10); // tried setting minimum capacity
for (int i = 0; i < roads.size(); i++) {
String from = roads.get(i).getFrom();
String to = roads.get(i).getTo();
for (int j = 0; j < places.size(); j++) { // this is where things go wrong, it doesn't iterate because the "j < places.size()" condition isn't met
if ((places.get(i).equals(from))==false) {
places.add(from);
}
if ((places.get(i).equals(to))==false) {
places.add(to);
}
}
}
return places;
}
Don't know why but the places-ArrayList doesn't set an initial capacity which leads to not being able to iterate places when I have to later on (the for-loop which deals with the j-variable).
Minimum capacity is different from size. Setting the capacity is just a hint to the list that it should have at least this much storage to avoid unnecessary array copies, but does not affect the size so even though you have the capacity for n elements the size()
can be less, and calling get(n-1)
might result in an IndexOutOfBoundsException
.
To create a list of size n that is filled with null
, try
List<String> myList = new ArrayList<String>(n);
for (int i = 0; i < n; ++i) { myList.add(null); }
The capacity attribute just gives the class a magnitude of how dimension its internal buffer. It does not add any values to the list (btw, which values would have been added?) so the list is still empty.
The only effect of capacity is to allow the class to avoid resizing its buffer (with the associated performance penalty) later in the execution. But it is not a hard limit. You can add or more elements at will as with any other List.
Use foreach
:
for(Road road : roads)
{
String from = road.getFrom();
String to = roads.getTo();
for(Places place: places)
{
if(!place.equals(from)) places.add(from);
if(!place.equals(to)) places.add(to);
}
}
ArrayList.ensureCapacity()
allocates enough memory to hold up to the given number of entries. It doesn't actually put anything into the ArrayList
.
ArrayList.size()
counts the number of actual entries, not the current capacity.
Your loop looks at places.size()
before you call places.add()
to actually put anything into places
. When places.size()
is called at the start of the loop it correctly returns 0 because at this point you haven't yet put anything into places
.
One other point. You have a method called places
and within that method a local variable also called places
. That is a recipe for confusion. You should use a different name for one of them.
精彩评论