I have a class Vehicule
and 3 subclasses Voiture
, Camion
and Moto
.
I also have a method getVehicules
for the all vehicules (i.e. camion, voiture, moto) but I want to print
a specific type like Voiture.
I don't know how to solve it .
List<Vehicule> vehicules = new ArrayList<>();
public void getVehicules() {
vehicules.forEach(vehicule->{
System.out.println(vehicule);
});
}
public void getVoitures() {
Iterator iterator = vehicules.iterator();
while(iterator.hasNext()) {
//I want to do a condtion if vehicule is voiture it will disaplay
if(vehicules.equals(voiture)) {
System.out.println(iterator);
}
}
}
CodePudding user response:
Check this out, instanceof would help here :-
class Vehicule {
}
class Voiture extends Vehicule {
@Override
public String toString() {
return "Voiture";
}
}
class Camion extends Vehicule {
@Override
public String toString() {
return "Camion";
}
}
class Moto extends Vehicule {
@Override
public String toString() {
return "Moto";
}
}
public class Operation {
static List<Vehicule> vehicules = new ArrayList<>();
public static void main(String[] args) {
vehicules.add(new Camion());
vehicules.add(new Moto());
vehicules.add(new Voiture());
//Prints all objects
getVehicules();
//Prints only voiture
getVoitures();
}
public static void getVehicules() {
vehicules.forEach(vehicule -> {
System.out.println(vehicule);
});
}
public static void getVoitures() {
Iterator iterator = vehicules.iterator();
while (iterator.hasNext()) {
Object vehicule = iterator.next();
if (vehicule instanceof Voiture) {
System.out.println(vehicule);
}
}
}
}
CodePudding user response:
How to compare two data type in Java You can get the type (a
java.lang.Class
) of an object usingobject.getClass()
.
You can compare two classes using equals(...)
; e.g.
if (obj1.getClass().equals(obj2.getClass())
You can test if an object has a specific class in a couple of ways
if (obj.getClass().equals(Car.class))
or
if (obj instanceof Car)
(They do slightly different things. The latter tests if obj
is a Car
or a subclass of Car
and will return false
if obj
is null
.)
There are methods on the Class
class that will give the classes simple name or its full name ... or you can just use the Class.toString()
method.
Just for the record, another way to solve the problem that doesn't involve using the class names would be to define a second (abstract) method in the superclass that returns a String that denotes the kind of the vehicle; e.g.
public abstract class Vehicle {
...
public abstract String getType();
}
public class Car extends Vehicle {
@Override
public String getType() {
return "Car";
}
}
CodePudding user response:
switch
expressions
In Java 14 , use switch
expressions.
Some untested code:
switch ( véhicule.getClass() ) {
case Voiture.class -> System.out.println( … );
case Camion.class -> System.out.println( … );
case Moto.class -> System.out.println( … );
}
Wrap that in a for-each loop.
for( Véhicule véhicule: véhicules)
{
…
}