简体   繁体   English

用多种对象类型填充ArrayList

[英]Populating an ArrayList with multiple object types

I am trying to create an ArrayList with multiple object types in Java. 我正在尝试用Java创建具有多个对象类型的ArrayList。 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. 我在Google上进行了搜索,但是找不到可以在我正在做的事情中使用的答案。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

First, you cannot have statements inside a class but outside a method, constructor, or initializer block. 首先,您不能在类内部但在方法,构造函数或初始化程序块外部具有语句。 Put that code in main . 将代码放在main

Second, call new Dragsters() , not "one", 0.6, 1000, 0.9, 3 . 其次,调用new Dragsters() ,而不是"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. Java不会接受参数,推导类型( Dragster ),创建该类型的对象并按照声明它们的顺序自动将它们分配给实例变量。 There is no such add method in ArrayList that takes those 5 arguments. ArrayList中没有使用这5个参数的add方法。

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. 第三,如果您确实想在创建Dragster时传递这些值,请在Dragsters中创建一个构造函数,该构造函数将使用5个参数并将它们明确分配给其实例变量。

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

Agree with @rgettman. 同意@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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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