这是我创建的玩具示例问题。我有一个 IP
类(class)。我想创建一个 IP
的数组列表像下面这样,但是没有用。
class IP{
private long d;
public IP(long d){
this.d = d;
}
}
class something{
public void some_method(){
HashMap<IP, ArrayList<IP>> ip_map = new HashMap<IP,ArrayList<IP>>();
......
IP ip_key = new IP(1);
IP ip2 = new IP(2);
IP ip3 = new IP(3);
// this is the line that always goes wrong
ip_map.put(ip_key, new ArrayList<IP>(ip2)) ;
ip_map.get(ip_key).add(ip3);
}
}
这总是失败。错误信息是:
error: no suitable constructor found for ArrayList(IP)
ip_map.put(ip_key, new ArrayList<IP>(ip2));
^
constructor ArrayList.ArrayList(int) is not applicable
(argument mismatch; IP cannot be converted to int)
constructor ArrayList.ArrayList() is not applicable
(actual and formal argument lists differ in length)
constructor ArrayList.ArrayList(Collection<? extends Vertex>) is not applicable
(argument mismatch; IP cannot be converted to Collection<? extends IP>)
1 error
是不是因为我的 IP 类没有实现 Collection 接口(interface)?我想知道这是否真的不可行:ip_map.put(ip_key, new ArrayList<IP>(ip2)) ;
更新:我知道我可以克服这个问题
ArrayList<IP> ip_list = new ArrayList<IP>();
ip_list.add(ip2);
ip_map.put(ip_key, ip_list);
但是我想知道是否有可能因为代码减少而像下面那样做?
ip_map.put(ip_key, new ArrayList<IP>(ip2)) ;
最佳答案
你打算用new ArrayList<IP>(ip2)
做什么? ?如果你想用 ip2
创建一个列表在其中,您需要实例化列表,然后添加它。喜欢:
List<IP> list = new ArrayList<IP>();
list.add(ip2)
检查 new ArrayList(int)
的 Java 文档构造函数 here了解 ArrayList(ip2) 将尝试做什么以及失败的原因。
如果你真的想缩短(不是真的简化)你的代码,你可以这样做:
import java.util.Arrays;
...
...
List<IP> list = new ArrayList<IP>(Arrays.asList(ip2));
关于Java:我是否过度简化了代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498206/