[英]Java: Checking if an IP address is in an Array List
有沒有特殊的方法來檢查arrayList中是否存在IP地址? 現在我有一個由IP地址字符串組成的arraylist(例如“192.168.0.4”等)。 收到數據包后,我想檢查數據包的IP地址是否屬於arraylist。
起初我認為這樣的事情就足夠了:
for (int i = 0; i < myList.size(); i++)
{
if (packet.getAddress().equals(InetAddress.getByName(myList.get(i))))
{
System.out.println("this packet's IP address is in list");
}
else
{
System.out.println("this packet's IP address is not in list!");
}
我認為其他聲明會解決這種情況,但我錯了。 任何建議將不勝感激。
我建議將ArrayList轉換為Set(不是在每次檢查之前,因為這將是不必要的開銷),這樣就可以避免for循環。 這只是一個問題
Set<InetAddress> mySet = new HashSet<InetAddress>(myList);
...
if(mySet.contains(packet.getAddress())) {
// ...
}
我想你也可以使用myList.contains,但我認為實現無論如何都會遍歷列表,所以使用Set會更快。
在知道IP不存在之前,您必須檢查整個列表:
boolean found = false;
for (int i = 0; i < myList.size() && !found; i++) {
if (packet.getAddress().equals(InetAddress.getByName(myList.get(i)))) {
found = true;
System.out.println("this packet's IP address is in list");
}
}
if (!found) {
System.out.println("this packet's IP address is not in list!");
}
問題是您要為每個與地址不匹配的項目打印消息。 相反,您可以在方法中封裝此功能,返回布爾值,然后執行打印:
public boolean isPackedInList() {
for (int i = 0; i < myList.size(); i++) {
if (packet.getAddress().equals(InetAddress.getByName(myList.get(i)))) {
return true;
}
}
return false;
}
然后使用它:
if (isPackedInList()) {
System.out.println("this packet's IP address is in list");
} else {
System.out.println("this packet's IP address is not in list!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.