[英]Object ArrayList For-Loop Error
I have an Object ArrayList and I need to use the toString() method of the Motor object, which is a parameter of the Vehicle object. 我有一个对象ArrayList,我需要使用Motor对象的toString()方法,该方法是Vehicle对象的参数。 My vehicle objects are in an ArrayList which is iterated through with a for-loop (I know a foreach loop would be easier, but this is part of the assignment)
我的车辆对象位于ArrayList中,该数组通过for循环进行迭代(我知道foreach循环会更容易,但这是分配的一部分)
Here is the code for the loop: 这是循环的代码:
for (int i = 0; i < VehicleList.size(); i++) {
System.out.println();
String info = VehicleList.get(i).toString();
Motor m = VehicleList.get(i).motor;
String motorInfo = m.toString();
System.out.println(info);
System.out.println(m);
}
There is an error that says " motor cannot be resolved or is not a field ". 出现错误,提示“ 电动机无法解析或不在字段中 ”。
All of the classes should allow this to work, unless of course there is a simple mistake I am missing. 所有的类都应该允许它起作用,除非我当然缺少一个简单的错误。
Here is the Motor class: 这是电机类:
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=
" + bhp + ", displacement= " + displacement;
}
}
Motors and Vehicles are intitialized here (In the TestVehicle class): 在这里初始化了汽车和车辆的使用(在TestVehicle类中):
//Motors
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Motor Hemi = new Motor("Hemi", 8, 707, 5.7);
Motor P90D = new Motor("P90D", 0, 762, 0.0);
//Vehicles
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, EcoBoost);
Vehicle v1 = new PassCar("Tesla", "Model S", 2016, 121000.0, 2, true, P90D);
Vehicle v2= new Truck("Dodge", "Ram", 2016, 46000.0, "pickup", 1500, Hemi);
PassCar and Truck are inherited classes of Vehicle with a few more attributes. PassCar和Truck是具有更多属性的Vehicle的继承类。 I can post the PassCar or Truck class if needed but I do not think that is where the problem is arising from.
如果需要,我可以发布PassCar或Truck类,但我认为这不是问题所在。 I believe it is coming from the For-Loop, specifically the line Motor m = VehicleList.get(i).motor;
我相信它是来自For-Loop,特别是行Motor m = VehicleList.get(i).motor; but I am not sure of how to fix it.
但我不确定该如何解决。
Vehicle Class: 车辆类别:
public class Vehicle {
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public void description() {
System.out.println("Description");
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
EDIT: There cannot be any Getters or Setters as per the assignment requirements, and it must be an ArrayList, not a regular List. 编辑:根据分配要求,不能有任何Getter或Setter,它必须是ArrayList,而不是常规List。 When I switch to I get the error "Type mismatch: cannot convert from ArrayList to ArrayList
当我切换到我时,出现错误“类型不匹配:无法从ArrayList转换为ArrayList
ArrayList<Object> VehicleList = new ArrayList<>(Arrays.asList(vehicles));
VehicleList
is declared to contain instances of Object
, so the compiler will only let you access methods and fields it knows exist on all instances of Object
. VehicleList
被声明为包含Object
实例,因此编译器将只允许您访问它在Object
所有实例上都存在的已知方法和字段。
Change it to ArrayList<Vehicle>
. 将其更改为
ArrayList<Vehicle>
。
Create an interface IMotor
which is used by Vehicle
class and Implemented in PassCar
and other implementation of vehicle. 创建一个接口
IMotor
,该接口由Vehicle
类使用,并在PassCar
和其他车辆实现中实现。
IMotor.java IMotor.java
public interface IMotor {
public Motor getMotor();
}
Motor.java 马达
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=" + bhp + ", displacement= " + displacement;
}
}
Vehicle.java Vehicle.java
public abstract class Vehicle implements IMotor{
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
PassCar 通行证
public class PassCar extends Vehicle{
protected Motor motor;
public PassCar(String make, String model, int year, double price, Motor motor) {
super(make, model, year, price);
this.motor = motor;
}
public Motor getMotor() {
return motor;
}
}
Test.java Test.java
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, EcoBoost);
List<Vehicle> vehicles = Arrays.asList(v0);
System.out.println(vehicles.get(0).getMotor());
}
}
First, mind the naming convention. 首先,请注意命名约定。 Variables should be named in
camcelCase
eg vehicleList instead of
VehicleList` 变量应在
camcelCase
中命名,例如vehicleList instead of
VehicleList`
I have an Object ArrayList
我有一个对象ArrayList
I believe you mean declaration of vehicleList
looks like ArrayList<Object> vehicleList
我相信你的意思是
vehicleList
声明看起来像ArrayList<Object> vehicleList
Then behavior is expected because compiler only knows that VehicleList.get(i)
is going to return you an Object
reference. 然后会出现预期的行为,因为编译器仅知道
VehicleList.get(i)
将向您返回Object
引用。 It can be a Vehicle
, but it can also be anything else. 它可以是
Vehicle
,也可以是其他任何东西。 So it won't allow you to access the motor
field, as there is simply no such field in Object
. 因此,它不允许您访问
motor
字段,因为Object
根本没有这样的字段。
Change your declaration to something like List<Vehicle> vehicleList
将声明更改为类似
List<Vehicle> vehicleList
However, as mentioned in other answer, it is not a good idea to access the field directly because of various reason. 但是,正如其他答案所述,由于各种原因,直接访问该领域并不是一个好主意。 A slightly less evil way is to have getter of
motor
. 一种较不那么邪恶的方法是使
motor
吸气。 (A better way is to provide meaningful behaviors instead of providing access to internal data) (更好的方法是提供有意义的行为,而不是提供对内部数据的访问)
Your problem is that motor
is not a member of the Vehicle
class, but you are trying to access it through an expression of type Vehicle
- namely vehicleList.get(i)
. 您的问题是
motor
不是Vehicle
类的成员,但是您正在尝试通过Vehicle
类型的表达式(即vehicleList.get(i)
访问它。 This is forbidden, because the compiler has no way of knowing that every possible kind of Vehicle
has a motor
. 这是禁止的,因为编译器无法知道每种可能的
Vehicle
都有一个motor
。 After all, what would happen if you added a Bicycle
class? 毕竟,如果您添加了
Bicycle
类,会发生什么?
To make this work, you should remove motor
from the Truck
and PassCar
classes, and add it to the Vehicle
class. 要使此工作正常进行,您应该从
Truck
和PassCar
类中删除motor
,并将其添加到Vehicle
类中。 That way, vehicleList.get(i).motor
would actually make sense, since the Vehicle
expression would be guaranteed to refer to a Vehicle
with a Motor
. 这样一来,
vehicleList.get(i).motor
实际上就有意义,因为可以保证Vehicle
表达式引用具有Motor
的Vehicle
。
It would also be recommended to use a getter for the motor
field - that is, have motor
as a private
field of the Vehicle
class, and write a method getMotor()
to return it. 还建议对
motor
字段使用吸气剂-也就是说,将motor
作为Vehicle
类的private
字段,并编写方法getMotor()
来返回它。 You could then write vehicleList.get(i).getMotor()
to get the Motor
object associated with one Vehicle
in the list. 然后,您可以编写
vehicleList.get(i).getMotor()
来获取与列表中的一个Vehicle
关联的Motor
对象。
Thanks to the help of all of your comments and my Java textbook, I managed to piece it together. 多亏了您的所有注释和Java教科书的帮助,我才得以将其拼凑起来。 Here is how I got it to work:
这是我的工作方式:
for (int i = 0; i < vehicleList.size(); i++) {
String motorInfo = "";
String info = "";
System.out.println();
if (vehicleList.get(i) instanceof PassCar) {
info = ((PassCar)vehicleList.get(i)).toString();
**motorInfo = ((PassCar)vehicleList.get(i)).motor.toString();**
}
else if(vehicleList.get(i) instanceof Truck) {
info = ((Truck)vehicleList.get(i)).toString();
**motorInfo = ((Truck)vehicleList.get(i)).motor.toString();**
}
Basically I had to use a polymorphic call and check if it was an instance of a PassCar or Truck. 基本上,我必须使用多态调用并检查它是否是PassCar或Truck的实例。 And as for the Array and ArrayList used during the Class, I edited them like this:
至于在课堂上使用的Array和ArrayList,我像这样编辑它们:
Vehicle [] vehicles = new Vehicle [3];
vehicles[0] = v0;
vehicles[1] = v1;
vehicles[2] = v2;
showVehicle(vehicles);
ArrayList<Vehicle> vehicleList = new ArrayList<Vehicle>(Arrays.asList(vehicles));
System.out.println();
System.out.println("Output from ArrayList in main: ");
Thank you for the help everyone! 谢谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.