【发布时间】:2015-05-25 10:49:22
【问题描述】:
是否可以在Java中以类似于此的样式制作数组,我已经搜索了一段时间并没有找到任何东西。
int[] foo = {
for(String arg:args)
return Integer.parseInt(arg);
};
【问题讨论】:
是否可以在Java中以类似于此的样式制作数组,我已经搜索了一段时间并没有找到任何东西。
int[] foo = {
for(String arg:args)
return Integer.parseInt(arg);
};
【问题讨论】:
不,但您可以这样做:
int[] foo = new int[args.length];
for(int i = 0; i < foo.length; i++) {
foo[i] = Integer.parseInt(args[i]);
}
【讨论】:
不完全是,但试试这个。
int[] foo = new int[args.length]; //Allocate the memory for foo first.
for (int i = 0; i < args.length; ++i)
foo[i] = Integer.parseInt(args[i]);
//One by one parse each element of the array.
【讨论】:
使用 Java 8,可以这样做:
int[] foo = Stream.of(args).mapToInt(str -> Integer.parseInt(str)).toArray();
【讨论】:
有点...从 Java 8 开始,我们有了可以模拟循环并允许我们执行类似操作的流
int[] arr = Arrays.stream(args).mapToInt(s -> Integer.parseInt(s)).toArray();
或使用method references的等效项
int[] arr = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();
【讨论】:
int[] foo = new int[arg.length];
for (int i =0;i<args.length;i++) foo[i]=Integer.parseInt(args[i]);
【讨论】:
没有数组,但你可以用List做类似的事情:
final String args[] = {"123", "456", "789"};
List<Integer> list = new LinkedList<Integer>(){
{
for (String arg: args){
add(Integer.parseInt(arg));
}
}
};
System.out.println(list); // [123, 456, 789]
使用数组,您必须执行以下操作:
int[] foo = new int[args.length];
for (int i = 0; i < foo.length; i ++) {
foo[i] = Integer.parseInt(args[i]);
}
【讨论】: