谁能告诉我这是怎么回事?在我看来,myObj 正在转换为 String[],因此可以在 for 循环中对其进行迭代。但它是作为 new String[] 构造的——为什么需要转换它?
public static void main(String args[]) {
Object myObj = new String[]{"one", "two", "three"};
for (String s : (String[])myObj) {
System.out.print(s + ".");
}
}
谢谢!
最佳答案
创建为 String[]
并不重要;你只有一个 Object
引用它。这与 for-each 无关;以下也不会编译:
Object myObj = new String[]{"one", "two", "three"};
System.out.println(myObj.length); // There is no Object.length
关于java - for-each 语法转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8114542/