I'm trying to figure out a nice way to iterate and print out the objects inside my ArrayList.
Problem is that i can't seem to reach the fields in which the user is typing the info of the objects (such as color and brand).
The new instance of an object looks like this:
Vehicle C = new Car(4, "Blue", "Honda");
Car (and other classes such as Bike, Bus etc) are subclasses of Vehicle.
The Vehicle class:
public class Vehicle {
public int pass = 0;
public int cost = 0;
public int size = 0;
public String brand = "";
public String color = "";
public Vehicle(){}
}
The Car class:
public class Car extends Vehicle{
// constructor
public Car(int passengers, String col, String brandOfVehicle){
if (passengers < 0 || passengers > 4){
throw new IllegalArgumentException();
}else
pass = passengers;
cost += pass*15 + 100;
size = 5;
color = col;
brand = brandOfVehicle;
}
} When trying to iterate over the objects:
Iterator<Object> it = Ferry.iterator();
while(it.hasNext()){
Object i = it.next();
System.out.println(i + " ");
}
When iterating over the objects I would like to reach the color and brand Strings as in i.color. But I'm guessing that since i is a new Object perhaps it doesn't get access to the fields and methods associated with Car, Bus etc?
Is there any way to get around this? Or is perhaps this not the actual problem?
I don't know what the type of Ferry
is, but perhaps Ferry.iterator()
should return an Iterator<Vehicle>
instead of Iterator<Object>
.
Then it.next()
would return a reference to a Vehicle
, which would allow you to access all the public members of Vehicle
.
Iterator<Vehicle> it = Ferry.iterator();
while(it.hasNext()){
Vehicle i = it.next();
System.out.println(i.color);
}
If Ferry
can contain objects that are not Vehicle
, you'll have to use casting :
Iterator<Object> it = Ferry.iterator();
while(it.hasNext()){
Object i = it.next();
if (i instanceof Vehicle)
System.out.println(((Vehicle)i).color);
}