【问题标题】:How to compare if one object is the same type as another如何比较一个对象是否与另一个对象相同
【发布时间】:2018-04-08 11:31:31
【问题描述】:

在下面的列表中,有 3 辆卡车,我需要用示例将拖车的数量加起来。

在第一个“if”中,我想比较车辆是否与卡车属于同一类型,但如果使用“equals”,则此代码不打印任何内容,并且可以肯定它应该打印 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);
            }
        }
    }
}

}

如何在不重写equal方法的情况下进行比较?

谢谢!

【问题讨论】:

标签: java


【解决方案1】:

除了instanceOf方法,你可以试试这些方法

Object.getClass() returns runtime type of object 

在您的代码示例中,if 语句可以以这种方式使用

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

if (Truck.class.isInstance(vehicle))

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) {
}

考虑到良好的面向对象设计,instanceOf、getClass、isInstance 方法绝不应在应用程序中使用。

【讨论】:

    【解决方案2】:

    equals方法使用对象的hash方法进行比较。

    看这个:https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

    最简单的方法是使用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);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2022-06-11
      • 1970-01-01
      • 2017-07-10
      相关资源
      最近更新 更多