class A {
public static void main(String args []){
int val = (int) ((Math.random) * 5);
String res = new String [ ]{"Rahul","Javed","Kunal","Ram"}[val];
System.out.println(res);
}
}
Run Code Online (Sandbox Code Playgroud)
当val的值为1时,打印了"Javed" - 但是在"String res ="表达式的末尾如何以及什么是[val].
someArray[index]是在特定索引中访问数组元素的方法.在这种情况下,您正在创建一个数组:
new String[] { "Rahul", "Javed", "Kunal", "Ram" }
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式访问元素:
new String[] { "Rahul", "Javed", "Kunal", "Ram" }[val]
Run Code Online (Sandbox Code Playgroud)
这类似于
someArray[val]
Run Code Online (Sandbox Code Playgroud)
val索引在哪里 请记住,Java(以及大多数编程语言)中的索引都以0开头.