为什么这会给出不同的输出。
LinkedList<Integer> blocked [] = new LinkedList[n+1];
int obstacles [][]= {{5, 5},{4 ,2},{2 ,3}};
CASE 1: Arrays.fill(blocked, new LinkedList<Integer>());
System.out.println(blocked);
OUTPUT :
[5, 2, 3]
[5, 2, 3]
[5, 2, 3]
[5, 2, 3]
[5, 2, 3]
CASE 2: for(int i=0;i<=n;i++)
blocked[i]= new LinkedList<Integer>();
OUTPUT : []
[3]
[]
[2]
[5]
为什么它的工作方式不同,在 arrays.fill 中使用新的链表是否发送相同的对象引用?
最佳答案
以下是您正在使用的 Arrays.fill() 的代码:
public static void fill(Object[] a, Object val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}
所以答案是肯定的,它使用相同的对象实例来填充数组。
关于java - Arrays.fill() 和用于初始化链表数组的 for 循环之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628820/