谁能告诉我这里发生了什么?它看起来像myObj被强制转换为String []所以它可以在for循环中迭代.但它被构造为新的String [] - 为什么需要进行转换?
public static void main(String args[]) {
Object myObj = new String[]{"one", "two", "three"};
for (String s : (String[])myObj) {
System.out.print(s + ".");
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
它被创建为一个并不重要String[]; 你只有一个Object参考.这与for-each无关; 以下内容不会编译:
Object myObj = new String[]{"one", "two", "three"};
System.out.println(myObj.length); // There is no Object.length
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |