Issue
I have Object:
static class Truck {
ArrayList<Integer> route = new ArrayList<Integer>();
double weight = 0;
int route_weight = 0;
Truck() {
}
Truck(ArrayList<Integer> route) {
Collections.copy(this.route, route);
}
//getters and setters
}
Objects pulling into this list:
static ArrayList<Truck> trucks=new ArrayList<Trucks>();
I'm trying to make a full copy of the list:
ArrayList<Truck> copy=new ArrayList<>();
copy=cloneList(trucks);
public static ArrayList<Truck> cloneList(ArrayList<Truck> trucksList) {
ArrayList<Truck> clonedList = new ArrayList<Truck>();
for (Truck truck : trucks) {
Truck w=new Truck(truck.getroute());
clonedList.add(w);
}
return clonedList;
}
But I'm getting a error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
getroute returns:
[0, 9, 11, 1, 15, 3, 0]
Solution
Collections.copy
requires that the size of the destination list is at least the size of the source list. Your this.route
has a size of 0 when you try to do the copy so you get an exception.
Instead use addAll
:
Truck(ArrayList<Integer> route) {
this.route.addAll(route);
}
Answered By - greg-449
Answer Checked By - Terry (JavaFixing Volunteer)