0

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!

1
  • You appear to be expecting the list to handle object construction for you, which it will not do. Construct a Dragsters object first, then pass it in and see. Commented Feb 11, 2015 at 0:56

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just want to add that calling your class Dragsters (plural) suggests a misunderstanding of how classes in Java work. The class is like a blueprint that each object is made from. It's not all of your objects together.
0

dragsterList.add(new Dragsters("one", 0.6, 1000, 0.9, 3));

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.