我需要得到一个String[]
出来的Set<String>
,但我不知道该怎么做.以下失败:
Map<String, ?> myMap = gpxlist.getAll();
Set<String> myset = myMap.keySet();
String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails.
Run Code Online (Sandbox Code Playgroud)
我该如何修复以使其有效?
如何将我的Kotlin转换Array
为varargs Java String[]
?
val angularRoutings =
arrayOf<String>("/language", "/home")
// this doesn't work
web.ignoring().antMatchers(angularRoutings)
Run Code Online (Sandbox Code Playgroud)
我有一个List<Thing>
,我想将它传递给声明的方法doIt(final Thing... things)
.有没有办法做到这一点?
代码看起来事情是这样的:
public doIt(final Thing... things)
{
// things get done here
}
List<Thing> things = /* initialized with all my things */;
doIt(things);
Run Code Online (Sandbox Code Playgroud)
该代码显然不能因为工作doIt()
需要Thing
不能List<Thing>
.
有没有办法传入List作为varargs?
这是在Android应用程序中,但我不明白为什么该解决方案不适用于任何Java
假设具有以下签名的方法:
public static void foo(String arg1, String args2, Object... moreArgs);
Run Code Online (Sandbox Code Playgroud)
跑步时......
ClassName.foo("something", "something", "first", "second", "third");
Run Code Online (Sandbox Code Playgroud)
......我会的moreArgs[0] == "first"
,moreArgs[1] == "second"
而且moreArgs[2] == "third"
.
但是假设我将参数存储在一个包含"first","second"和"third" 的ArrayList<String>
被调用arrayList
中.
我想打电话foo
让moreArgs[0] == "first"
,moreArgs[1] == "second"
并且moreArgs[2] == "third"
使用arrayList
作为参数.
我天真的尝试是......
ClassName.foo("something", "something", arrayList);
Run Code Online (Sandbox Code Playgroud)
......但这会给我moreArgs[0] == arrayList
一些不是我想要的东西.
传递arrayList
给上述foo
方法的正确方法是什么moreArgs[0] == "first"
,moreArgs[1] == "second"
以及moreArgs[2] == "third"
?
请注意,arrayList …
我知道Java"..."数组参数语法可以作为参数接收数组,或只传递给方法的许多参数.但是,我注意到它也适用于Collections:
public static void main(String[] args) {
Collection<Object> objects = new ArrayList<>();
test(objects);
}
public static void test (Object...objects) {
System.out.println("no compile errors");
}
Run Code Online (Sandbox Code Playgroud)
这编译并运行,我无需调用该toArray()
方法.现场背后发生了什么?此语法是否有其他"自动转换"方法?
顺便说一下,我正在使用Java 1.7.
我有一个函数 ( findByNames
) 接受传播参数,如下例所示:
List<Users> findByNames(String... names)
{
...
}
Run Code Online (Sandbox Code Playgroud)
作为参数,我有一个列表:
List<String> names = asList("john","abraham");
Run Code Online (Sandbox Code Playgroud)
所以我想将names
列表转换为传播对象以使用findByNames
函数,这可以使用 Java 8 吗?我试过这个解决方案:
MapUtils.getMap(names.toArray(new String[names.size()]))
Run Code Online (Sandbox Code Playgroud)
但它不起作用!
谢谢你的时间。