可以在 Java 中从另一个数组引用一个数组元素吗?
是的,你可以 -
int [] myArray1 = {23, 45, 78, 90, 10};
int [] myArray2 = {23, 45, myArray1[2], 90, 10};但是,一旦你这样做,第二个数组将存储该值的引用,而不是整个数组的引用。因此,数组中的任何更新都不会影响所引用的值 -
例如
import java.util.Arrays;
public class RefferencingAnotherArray {
public static void main(String args[]) {
int [] myArray1 = {23, 45, 78, 90, 10};
int [] myArray2 = {23, 45, myArray1[2], 90, 10};
System.out.println("Contents of the 2nd array");
System.out.println(Arrays.toString(myArray2));
myArray1[2] = 2000;
System.out.println("Contents of the 2nd array after updating ::");
System.out.println(Arrays.toString(myArray2));
System.out.println("Contents of the 1stnd array after updating ::");
System.out.println(Arrays.toString(myArray1));
}
}输出
Contents of the 2nd array [23, 45, 78, 90, 10] Contents of the 2nd array after updating :: [23, 45, 78, 90, 10] Contents of the 1stnd array after updating :: [23, 45, 2000, 90, 10]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP