Reputation: 925
Well hi there! I am making a game called DoorElementals, and I want to do this:
ArrayList<Color> colors = new ArrayList<Color>();
public Door(Color... colors) {
this.colors.add(colors);
}
public void addColor(Color... c){
this.colors.add(c);
}
But colors
is an array while this.colors
is an ArrayList
.
How should I go about this?
Upvotes: 2
Views: 110
Reputation: 2243
DO NOT USE Arrays.asList
. Depending on the amount of calls you do, it will impact the performance, since everytime you call the asList
method, a new List
is created.
You can, and should, use:
public Door(Color... colors) {
addAll(colors);
}
public void addAll(Color... colors) {
for (Color color : colors) {
myList.add(color);
}
}
Upvotes: 1
Reputation: 362
The java.util.Arrays
class provides a method to convert from an array to a List
.
ArrayList<Color> colors = new ArrayList<Color>();
public Door(Color... colors) {
this.colors.addAll(Arrays.asList(colors));
}
public void addColor(Color... c){
this.colors.addAll(Arrays.asList(c));
}
A better practice would be to make your constructor take a Collection
instead of a using the varargs.
List<Color> colors = new ArrayList<Color>();
public Door(Collection<Color> colors) {
this.colors.addAll(colors);
}
Upvotes: 2