简体   繁体   English

检查对象是否等于Java中存储在对象中的数据

[英]check object equals data stored in object in java

I have an IPAdress.java class which has a constructor with int array to store IP address. 我有一个IPAdress.java类,该类具有带int数组的构造函数来存储IP地址。 I have to check that the object passed as parameter equals the IP address stored in the object. 我必须检查作为参数传递的对象是否等于存储在对象中的IP地址。 I tried something like this: 我尝试过这样的事情:

    public boolean isTheSame(IPAdress p){
        if(????) {
            return true;
        } else {
           return false;
        }
    }

And I have another method where I create the object 我还有另一种创建对象的方法

    public static IPAdress fromString(String ipStr) {
    int[] arr = new int[4];
    String[] split = ipStr.split("\\.");
    for(int i=0;i<4;i++){
        arr[i]=Integer.parseInt(split[i]);
        System.out.println(arr[i]);
    }
    IPAdress p = new IPAdress (arr);
    return p;
}

Assuming you have so way of getting the internal representation (eg, let's assume your method is called asArray() , you can use java.util.Arrays.equals(int[], int[]) ): 假设您具有获取内部表示形式的方式(例如,假设您的方法名为asArray() ,则可以使用java.util.Arrays.equals(int [],int []) ):

public boolean isTheSame(IPAdress p) {
    return Arrays.equals(asArray(), p.asArray());
}

EDIT: 编辑:
BTW, Note that the canonical Java way of doing this would be to override eauls(Object) : 顺便说一句,请注意,规范的Java方法是覆盖eauls(Object)

@Override
public boolean equals(Object o) {
    if (!(o instanceof IPAddress) {
        return false;
    }
    return Arrays.equals(asArray(), ((IPAddress) o).asArray());
}

Get rid of your isTheSame() method. 摆脱您的isTheSame()方法。 Just use the inbuilt equals method which designed for the same purpose. 只需使用为相同目的而设计的内置equals方法。

Override the equals method in your IPAdress class and provide your implementation there to check the equality. 重写IPAdress类中的equals方法,并在此处提供实现以检查是否相等。 For ex: return true if both objects ip is same etc ... 例如:如果两个对象ip相同则返回true ...

So you can implement the interface Comparable , you class IPAddress will be : public class IPAddess implements Comparable , then you should implement the methods 因此,您可以实现Comparable接口,您的IPAddress类将是:public class IPAddess实现Comparable,那么您应该实现方法

@Override 
public int compareTo(IPAddress ipAddress) {  }
@Override 
public boolean equals(Object obj) {  }
A class that overrides equals must also override hashCode.
@Override 
public int hashCode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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