0

I am looking to populate an array in the constructor with string values whenever a new instance is created. I am getting the following error in my code when I try to create an instance.

Array initialiser not allowed here.

Main Class

public static void main(String[] args) {
    .....
    Activities coldDrink = new Activities("string", 1, 1, {"string", "stringOne", "stringTwo"});
    ....
}

Activities Class

public class Activities {
  private String activityName;
  private int numberEssentialSensors;
  private int numberOptionalSensors;
  private ArrayList sensorList = null;


  Activities(String actName, int essSensors, int optSensors, ArrayList arrayValues) {
    this.activityName = actName;
    this.numberEssentialSensors = essSensors;
    this.numberOptionalSensors = optSensors;
    this.sensorList = arrayValues;

  }
Colin747
  • 4,885
  • 16
  • 66
  • 111
  • Are you doing that in the constructor? Please note that usage of raw-type collections is not encouraged. – Maroun Nov 20 '15 at 11:45
  • Related: http://stackoverflow.com/questions/21696784/how-to-declare-an-arraylist-with-values – Maroun Nov 20 '15 at 11:48

1 Answers1

3

{"string", "stringOne", "stringTwo"} is an array initialization expression, not an ArrayList. You can use new ArrayList(Arrays.asList("string", "stringOne", "stringTwo")) instead.

It would be better to use ArrayList<String> instead of the raw type though.

Activities coldDrink = new Activities("string", 1, 1, new ArrayList<String>(Arrays.asList("string", "stringOne", "stringTwo"));
Eran
  • 374,785
  • 51
  • 663
  • 734