Reputation: 53
I am trying to create an ArrayList with multiple object types in Java. So far I have
import java.util.ArrayList;
public class DragRace {
public class Dragsters {
public String name;
public double rTime;
public int torque;
public double traction;
public int burnout;
}
ArrayList<Dragsters> dragsterList = new ArrayList<Dragsters>();
dragsterList.add("one", 0.6, 1000, 0.9, 3);
But it gives me the error
cannot resolve symbol 'add.'
I have searched on Google but could not find an answer that could be used in what I'm doing. Any help would be greatly appreciated. Thanks!
Upvotes: 0
Views: 606
Reputation: 8021
Agree with @rgettman. The revised code would look like below.
public class DragRace {
public class Dragsters {
Dragsters(String name, double rTime, int torque, double traction, int burnout){
this.name = name;
this.rTime = rTime;
this.torque = torque;
this.traction = traction;
this.burnout = burnout;
}
String name;
int burnout double rTime;
int burnout int torque;
int burnout double traction;
int burnout int burnout;
}
ArrayList<Dragsters> dragsterList = new ArrayList<Dragsters>();
dragsterList.add(new Dragsters("one", 0.6, 1000, 0.9, 3));
Upvotes: 0
Reputation: 178263
First, you cannot have statements inside a class but outside a method, constructor, or initializer block. Put that code in main
.
Second, call new Dragsters()
, not "one", 0.6, 1000, 0.9, 3
. Java will not take arguments, deduce the type (Dragster
), create an object of that type, and automatically assign them to instance variables in the order in which they're declared. There is no such add
method in ArrayList
that takes those 5 arguments.
Third, if you do want to pass those values when creating a Dragster
, then create a constructor in Dragsters
that will take 5 parameters and explicitly assign them to its instance variables.
Upvotes: 1