private static ArrayList<String> places(ArrayList<Road> roads) {
ArrayList<String> places = new ArrayList<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 callingget(n-1)might result in anIndexOutOfBoundsException.To create a list of size n that is filled with
null, try