这是我创建的玩具示例问题。我有一个IP
课程。我想创建一个IP
的arraylist,如下所示,但它没有用。
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接口吗?我想知道这是否真的不可行: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)) ;
答案 0 :(得分:4)
您打算如何处理new ArrayList<IP>(ip2)
?如果要在其中创建包含ip2
的列表,则需要实例化列表,然后添加它。像:
List<IP> list = new ArrayList<IP>();
list.add(ip2)
检查java文档中的new ArrayList(int)
构造函数here,了解ArrayList(ip2)将尝试做什么以及失败的原因。
如果你真的想缩短(不简化)你的代码,你可以这样做:
import java.util.Arrays;
...
...
List<IP> list = new ArrayList<IP>(Arrays.asList(ip2));
答案 1 :(得分:1)
集合构造函数不支持单个元素或数组,因为它们不是API意义上的集合。您可以传递集合以初始填充新集合,也可以使用表示内部分配的初始容量的数字。
如果您正在寻找使用单个元素的不可修改集合的有效表示,请查看Collections.singleton(T)
,Collections.singletonList(T)
或Collections.singletonMap(K, V)
。