所以我有这个代码并打印出来:
import java.util.*;
public class Reverse_Copy {
public static void main(String[] args){
//create an array and covert to list
Character[] ray = {'p','w','n'};
List<Character> l = new ArrayList<Character>(Arrays.asList(ray));
System.out.println("List is: ");
output(l);
//reverse and print out the list
Collections.reverse(l);
System.out.println("After reverse: ");
output(l);
//create a new array and a new list
Character[] newray = new Character[3];
List<Character> listCopy = new ArrayList<Character>(Arrays.asList(newray));
//copy contens of list l into list listCopy
Collections.copy(listCopy, l);
System.out.println("Copy of list: ");
output(listCopy);
//fill collection with crap
Collections.fill(l,'X');
System.out.println("After filling the list: ");
output(l);
}
private static void output(List<Character> thelist){
for(Character thing: thelist)
System.out.printf("%s ", thing);
System.out.println();
}
}
这是印刷品:
List is:
p w n
After reverse:
n w p
Copy of list:
n w p
这是与enhanced for loops
括号相同的代码。
import java.util.*;
public class Reverse_Copy {
public static void main(String[] args){
//create an array and covert to list
Character[] ray = {'p','w','n'};
List<Character> l = new ArrayList<Character>(Arrays.asList(ray));
System.out.println("List is: ");
output(l);
//reverse and print out the list
Collections.reverse(l);
System.out.println("After reverse: ");
output(l);
//create a new array and a new list
Character[] newray = new Character[3];
List<Character> listCopy = new ArrayList<Character>(Arrays.asList(newray));
//copy contens of list l into list listCopy
Collections.copy(listCopy, l);
System.out.println("Copy of list: ");
output(listCopy);
//fill collection with crap
Collections.fill(l,'X');
System.out.println("After filling the list: ");
output(l);
}
private static void output(List<Character> thelist){
for(Character thing: thelist){
System.out.printf("%s ", thing);
System.out.println();
}
}
}
这是印刷品:
List is:
p
w
n
After reverse:
n
w
p
Copy of list:
n
w
p
After filling the list:
X
X
X
我发现这非常奇特,简单的括号与打印的方式有什么关系?有关为什么会发生这种情况的任何想法?如果你不相信我,你可以自己测试一下。我发现没有任何理由可以解决这个问题。非常奇怪。
编辑:重复网站中的答案仅证明它不会改变任何内容。证明如何添加花括号会改变事物而不是保持一致。
答案 0 :(得分:1)
当省略for
循环中的括号时,只执行第一行:
for(Character thing: thelist)
System.out.printf("%s ", thing);
System.out.println();
哪个会为printf
中的每个元素执行thelist
行,然后只执行一次println
。不要让缩进愚弄你。
和
for(Character thing: thelist){
System.out.printf("%s ", thing);
System.out.println();
}
这将为printf
中的每个元素执行println
行和thelist
行。