我想建立和IP地址管理工具。 我想將使用的IP存儲在數據庫中,並在設備上使用IP地址 。我希望能夠將「已使用」的ips拔出,並將它們與來自給定子網的IP列表進行比較,並確定該IP是「已使用」還是「可用」。 我需要「可用」列表來生成一個列表,我可以選擇添加到新設備,而不必選擇「已用」ip。在Java中,如何比較兩個對象的值?
這是我試過的,但它似乎沒有比較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;
}
@RC .:這不會幫助解決問題。他想要一個簡單的包含與否,而不是排名或排序。 –
如果你自己創建了這個IPAddress類型,我認爲你需要定義equals方法來告訴它如何進行比較。我只是用一個字符串來表示IP。請參閱http:// stackoverflow。com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java – developerwjk