简体   繁体   中英

How to compare if one object is the same type as another

In the list below there are 3 trucks and I need to add up how many are trailers with example.

In the first 'if' I am wanting to compare if the vehicle is of the same type as a truck, but with the 'equals', this code is not printing anything and the certainty was that it should print 3.

import java.util.ArrayList;
import java.util.Collection;

public class TesteTest {

public static void main(String[] args) {

    Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
    vehicles.add(new Car());
    vehicles.add(new Car());
    vehicles.add(new Truck());
    vehicles.add(new Truck());
    vehicles.add(new Truck());

    int counter = 0;
    Truck truck = new Truck();
    for (Vehicle vehicle : vehicles) {
        System.out.println();
        if (vehicle.equals(truck)) {
            truck = (Truck) vehicle;
            if (truck.hasTruck()) {
                counter++;
                System.out.println(counter);
            }
        }
    }
}

}

How can I compare without rewriting the equal method?

Thanks!

The equals method uses the hash method of the object to compare.

Look this: https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

The simplest way to do this is by using the instanceof operator .

public static void main(String[] args) {
    List<Vehicle> vehicles = new ArrayList();
    vehicles.add(new Car());
    vehicles.add(new Car());
    vehicles.add(new Truck());
    vehicles.add(new Truck());
    vehicles.add(new Truck());

    int counter = 0;
    for (Vehicle vehicle : vehicles) {
        if (vehicle instanceof Truck) {
            counter++;
        }
    }
    System.out.println(counter);
}

You can try these methods other than instanceOf method

Object.getClass() returns runtime type of object 

In your code sample if statement can be used in this way

if (vehicle.getClass() == Truck.class)

OR

if (Truck.class.isInstance(vehicle))

OR

try {
    Truck truck = (Truck) vehicle;
    // No exception: obj is of type Truck or IT MIGHT BE NULL!
   //here null value will also be type casted if present
} catch (ClassCastException e) {
}

Considering the good object oriented design the instanceOf, getClass, isInstance methods should never be used in the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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