本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>
提问:如何将ArrayList传递给varargs方法参数?
我有一个ArrayList的实例 locations:
ArrayList<WorldLocation> locations = new ArrayList<WorldLocation>();/
我调用该实例的如下方法
.getMap();
该方法的方法参数为
getMap(WorldLocation... locations)
我遇到的问题是我不确定如何传参。
我尝试
.getMap(locations.toArray())
getMap不接受这种传参方式,因为它不接受Objects []。
现在,如果我使用
.getMap(locations.get(0));
它会完美地工作...但是我需要以某种方式传递所有location...我当然可以不断添加locations.get(1), locations.get(2)等等,但是数组的大小会有所不同。我只是不习惯使用ArrayList
最简单的方法是什么?
回答:
使用toArray(T[] arr)方法
.getMap(locations.toArray(new WorldLocation[locations.size()]))
(toArray(new WorldLocation[0])也可以,但是您会无缘无故地创建一个零长度的数组。)
这是一个完整的示例:
public static void method(String... strs) {
for (String s : strs)
System.out.println(s);
}
...
List<String> strs = new ArrayList<String>();
strs.add("hello");
strs.add("world");
method(strs.toArray(new String[strs.size()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
回答2:
在Java 8中:
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
回答3:
有很多种方式实现:
方法1:
getMap(locations.toArray(new WorldLocation[locations.size()]));
方法2:
//当你仅需要传入一个空参数的时候
getMap(locations.toArray(new WorldLocation[0]));
方法3:
getMap(new WorldLocation[locations.size()]);
传入一个和locations等大的空参数的时候,这样会方便你进行遍历修改。 回答4:
热心网友甚至提供了KOTLIN的解决方案
fun log(properties: Map<String, Any>) {
val propertyPairsList = properties.map { Pair(it.key, it.value) }
val bundle = bundleOf(*propertyPairsList.toTypedArray())
}