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]
CodePudding user response:
In addition to greg-449's answer, I would like to point out that, instead of creating your ArrayList directly when you declare it, you could also create it in the constructor instead, making use of the ArrayList constructor which takes another list as its argument.
That would change your code to:
Truck() {
this.route = new ArrayList<>();
}
Truck(ArrayList<Integer> route) {
this.route = new ArrayList<>(route);
}
The newly created list will then contain all of the elements from the route list, in the same order.
CodePudding user response:
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);
}
