简体   繁体   中英

Adding an Array to an ArrayList

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?

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);
}

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM