【问题标题】:ArrayList.get() returns pointer not value? [duplicate]ArrayList.get() 返回指针而不是值? [复制]
【发布时间】:2017-02-20 21:43:51
【问题描述】:

ArrayList.get(index) 是否只返回索引处元素的值或指向该元素的指针?我问这个是因为它没有像我预期的那样执行

List<List<Integer>> myList; 
myList = new ArrayList<>(Collections.nCopies(n, new ArrayList<>()));
           .
           .
           .
List tempList = this.myList.get(x);
tempList.add(i);
this.myList.set(i,tempList);

不是在索引 x 处将元素添加到数组中,并将新列表存储在索引 i 处,而是在两个位置追加元素,因此列表大小不是增加,而是最后一个元素的 n 倍

【问题讨论】:

  • 你读过stackoverflow.com/questions/40480/… 吗?看看这是否回答了你的问题。
  • 所有对象类型的 Java 变量都是引用,其行为非常类似于指针。
  • 我搜索了但没有看到这个,谢谢

标签: java arraylist get


【解决方案1】:

你看错地方了。

这段代码绝对没有错:

List tempList = this.myList.get(x);
tempList.add(i);
this.myList.set(i,tempList);

除了可以缩写成这样:

List tempList = this.myList.get(x);
tempList.add(i);

(除了您使用的是List,这是一种原始数据类型,这也意味着您没有启用警告,但这是另一回事。)

你的问题在这里:

myList = new ArrayList<>(Collections.nCopies(n, new ArrayList<>()));

如果您查看Collections.nCopies() 的实现,您会发现它在内部使用了一个特殊列表,其中包含只有一个元素,即您给它的元素,无论您请求哪个索引,它都会返回相同的原始元素。

因此,您没有以 n 开头的列表;你只有一个列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多