java自己的equals方法在我的代码中工作不正确

ie3xauqp  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(308)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

23天前关门了。
改进这个问题
我正在写一个程序,在我写的一些代码中,我必须比较 ID 我拥有的东西和 ID 对象所在的列表中的对象。但是 equals () 方法无法正常工作。调试时,应该返回的部分 true 退货 false 因为if语句不起作用。这个 this 对象和我拥有的对象在图片中。你能告诉我我做错了什么吗?如果你需要它,我会把它上传到github,因为我的项目中的代码很长。你可以从那里下载。
github项目链接:https://github.com/rootroxox/error
等于方法的部分工作不正确:

case "TransferCargo" -> {
                    System.out.println("Readed Command: "+data);
                    String vehicleID = datas[1];
                    int distance = Integer.parseInt(datas[2]);
                    int load = Integer.parseInt(datas[3]);

                    for (Vehicle vehicle : vehicleList) {
                        System.out.println(vehicleID+" "+vehicle.getId());
                        if (vehicle.getId().equals(vehicleID)) {  ------------>>>>>>>>>>>>>> When vehicle.getID() = S00120 and vehicleID = S00120, equals method returns  false...
                            switch (vehicle.getType()) {
                                case "Plane":
                                    for (Plane plane : planeList) {
                                        if (plane.getCrewMembers().size() >= 3 && plane.getPilot() != null) {
                                            int maxLoad = (plane.getMotorCount() + plane.getCrewMembers().size() + 2) * 10;
                                            int maxDistance = (plane.getFuel()) / (((plane.getWeight() + load) / 10) + (plane.getMotorCount() / 2));
                                            if (distance <= maxDistance && load <= maxLoad && plane.getFuel() >= plane.getFuel() - distance) {
                                                plane.setFuelAmount(plane.getFuel() - distance);
                                                System.out.println("Cargo Mission Accomplished by " + vehicleID);
                                                break;
                                            }
                                            else{
                                                System.out.println("Cargo Mission Does NOT Accomplished by " + vehicleID);
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                case "Truck":
                                    for (Truck truck : truckList) {
                                        if (truck.getDriver() != null){
                                            int maxLoad = ((truck.getEngineVolume()/1000)+(truck.getTorque()/100))*3;
                                            int maxDistance = truck.getFuel()*10/(((load+truck.getWeight())/30)+truck.getEngineVolume()/2000);
                                            if (distance <= maxDistance && load <= maxLoad && truck.getFuel() >= truck.getFuel() - distance) {
                                                truck.setFuelAmount(truck.getFuel() - distance);
                                                System.out.println("Cargo Mission Accomplished by " + vehicleID);
                                                break;
                                            }
                                            else{
                                                System.out.println("Cargo Mission Does NOT Accomplished by " + vehicleID);
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                case "Ship":
                                    for (Ship ship : shipList) {
                                        if (ship.getCaptain() != null && ship.getCrewMembers().size() >= 5){
                                            int maxLoad = ((ship.getEngineOutput()/1000)+ship.getCrewMembers().size())*15;
                                            int maxDistance = ship.getFuel()*20/(((load+ship.getWeight())/100)+(ship.getEngineOutput()/10000));
                                            if (distance <= maxDistance && load <= maxLoad && ship.getFuel() >= ship.getFuel() - distance) {
                                                ship.setFuelAmount(ship.getFuel() - distance);
                                                System.out.println("Cargo Mission Accomplished by " + vehicleID);
                                                break;
                                            }
                                            else{
                                                System.out.println("Cargo Mission Does NOT Accomplished by " + vehicleID);
                                                break;
                                            }
                                        }
                                    }
                                    break;
                            }
                            break;
                        }
                    }
                }

bvk5enib

bvk5enib1#

覆盖等于

你需要实施 Object::equals 在你自己的班级里。否则java默认实现 equals 作为身份的比较(两个引用指向同一个对象,同一块内存)。
重写时 equals 要提供自己的比较逻辑,请始终实现 hashCode 也。ide可以为您生成此代码,但您需要确定在确定相等性时要比较哪些成员字段。
所有这些已经在堆栈溢出上被多次讨论过了。因此,搜索以了解更多信息。
例子:

package work.basil.example;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Invoice
{
    private List < LineItem > lineItems;
    private LocalDate invoiceDate;
    private Integer invoiceNumber;

    public Invoice ( List < LineItem > lineItems , LocalDate invoiceDate , Integer invoiceNumber )
    {
        this.lineItems = new ArrayList < LineItem >( lineItems );  // Shallow copy of the collection, for defensive programming.
        this.invoiceDate = invoiceDate;
        this.invoiceNumber = invoiceNumber;
    }

    public List < LineItem > getLineItems ( ) { return List.copyOf( this.lineItems ) ; }  // Shallow copy of the collection, for defensive programming.

    public void setLineItems ( List < LineItem > lineItems ) { this.lineItems = new ArrayList < LineItem >( lineItems ); }  // Shallow copy of the collection, for defensive programming.

    public LocalDate getInvoiceDate ( ) { return this.invoiceDate; }

    public void setInvoiceDate ( LocalDate invoiceDate ) { this.invoiceDate = invoiceDate; }

    public Integer getInvoiceNumber ( ) { return this.invoiceNumber; }

    public void setInvoiceNumber ( Integer invoiceNumber ) { this.invoiceNumber = invoiceNumber; }

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        Invoice invoice = ( Invoice ) o;
        return getInvoiceNumber().equals( invoice.getInvoiceNumber() );
    }

    @Override
    public int hashCode ( )
    {
        return Objects.hash( getInvoiceNumber() );
    }

    @Override
    public String toString ( )
    {
        return "Invoice{ " +
                "lineItems=" + lineItems +
                " | invoiceDate=" + invoiceDate +
                " | invoiceNumber=" + invoiceNumber +
                " }";
    }
}

记录

java的新记录特性使这变得更容易。
java中的记录是一种特殊的类,它主要是一个不可变的数据载体。默认情况下,记录提供 equals 它比较每个成员字段的值。
记录还提供 hashCode , toString 、访问器和构造函数。
下面是一个例子,一个 record 等级 Appointment . 我们只在类的名称后面声明成员字段。请注意,我们可以在这个类定义的花括号中只编写零行代码。

package work.basil.example;

import java.time.*;

public record Appointment(String description , LocalDateTime start , ZoneId timeZone , Duration duration)
{
}

使用那个记录类。我们创建了两个类似的 Appointment 只有年份不同。

Appointment appointment1 =
        new Appointment(
                "Acupuncture" ,
                LocalDateTime.of( 2021 , Month.JANUARY , 23 , 15 , 30 , 0 ) ,
                ZoneId.of( "America/Edmonton" ) ,
                Duration.ofMinutes( 90 )
        );
// Similar, but change the year.
Appointment appointment2 =
        new Appointment(
                "Acupuncture" ,
                LocalDateTime.of( 2022 , Month.JANUARY , 23 , 15 , 30 , 0 ) ,
                ZoneId.of( "America/Edmonton" ) ,
                Duration.ofMinutes( 90 )
        );

boolean appointmentsAreEqual = appointment1.equals( appointment2 );
System.out.println( "appointmentsAreEqual = " + appointmentsAreEqual );

运行时:
appointmentsareequal=错误

相关问题