在Java中,如何比较两个对象的值?

0 java compare arraylist

我想构建和IP地址管理工具.我想在数据库中存储使用过的IP,其中包含使用IP的设备的信息.我希望能够将"已使用"的ips拉出来并将它们与来自给定子网的IP列表进行比较,并确定ip是"已使用"还是"可用".我需要"可用"列表来生成一个列表,我可以选择添加到新设备,而不选择"已使用"的IP.

这是我尝试过的,但它似乎并没有比较IPAddress类型的两个对象.

    ArrayList<IPAddress> used = new ArrayList<>();
    ArrayList<IPAddress> available = new ArrayList<>();
    ArrayList<IPAddress> subnet = new ArrayList<>();

    //I reference my IPAddress class which has four int fields:
    //oct_1, oct_2, oct_3, oct_4  
    //the constructor for IPAddress takes for Ints and I build my IPAddress
    //from the for octets.

    //build a list of all ips in the subnet 10.50.2.0 - 10.50.2.255
    //assuming a class C subnet 255.255.255.0
    for(int i = 0; i < 256; i++){
        subnet.add(new IPAddress(10,50,2,i));
    }

    //identify used ips.  Eventually want to pull these from a database
    //but for now these are just random IP's representing possible used IPs
    used.add(new IPAddress(10,50,2,3));
    used.add(new IPAddress(10,50,2,5));
    used.add(new IPAddress(10,50,2,9));
    used.add(new IPAddress(10,50,2,13));
    used.add(new IPAddress(10,50,2,17));
    used.add(new IPAddress(10,50,2,22));


    //**** NEEDED CODE ********
    //i want to iterate through each IP in the subnet and check if it's in
    //the 'used' list.  If it IS NOT add the ip to the 'available' list.

    //my failed try      
    for(IPAddress ip : subnet){
        if(!used.contains(ip)){ //if ip is NOT in used add it to available
            available.add(ip);
        }
    }



    //print results out to the screen          
    for(IPAddress ip : available){
        System.out.println(ip.toString() + " is available.");
    }       

    for(IPAddress ip: used){
        System.out.println(ip.toString() + " is used.");
    }




//********************  Here is my IPAddress Class if it helps ****************
public class IPAddress {
private int oct_1 = 0;
private int oct_2 = 0;
private int oct_3 = 0;
private int oct_4 = 0;

public IPAddress(int Oct_1, int Oct_2, int Oct_3, int Oct_4){
   oct_1 = Oct_1;
   oct_2 = Oct_2;
   oct_3 = Oct_3;
   oct_4 = Oct_4;
}

@Override
public String toString(){
    String ipAddress = "";

    if(getOct_1() != 0){
    ipAddress = getOct_1() + "." + getOct_2() + "." + getOct_3() + "." + getOct_4();
           }
    return ipAddress;

}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

contains方法将使用equals.确保您覆盖了班级中的equals方法IPAddress.

另外,Javadocsequals表示在hashCode重写时应该覆盖该方法equals.

指示某个其他对象是否"等于"此对象.

请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.

  • 不要忘记也应该注意hashCode方法也应该被覆盖. (5认同)