当我在 java 中使用链表时,它似乎不是“按值传递";再说了,谁能解释一下? [英] when I use linkedlist in java, it seems not to "pass by value" anymore, anyone could explain?

查看:50
本文介绍了当我在 java 中使用链表时,它似乎不是“按值传递";再说了,谁能解释一下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

public static void main(String[] args)throws InterruptedException {   

    List<String> l1 = new LinkedList<String>();
    String[] s1 = {"aa","bb","cc","dd"};
    for(String k : s1)
        l1.add(k);

    removeStuff(l1,1,2);
    printList(l1);

}

private static void printList(List<String> l) {
    for(String b : l){
        System.out.print(b + ' ');
}

private static void removeStuff(List<String> l, int i, int j) {
    l.subList(1, 3).clear();
}

它将打印 aa dd 而不是 aa bb cc dd.所以我只是想知道,既然 java 是按值传递",那么如何通过 removeStuff 方法更改链表 l1?

it will print aa dd instead of aa bb cc dd. So I am just wondering that, since java is "pass-by-value", how could the linkedlist l1 be changed by the method removeStuff?

推荐答案

Java 是按值传递的,但传递的值是对内存中对象的引用.具体来说 l1 指向一个列表,当你调用一个方法时,变量 l1 没有被传递(即通过引用传递),而是 的值l1 被传递,这个值是对同一个对象的引用.如果您使用不同的 List 重新分配参数 l,则调用方中的变量 (l1) 不变.

Java is pass by value, but the value passed is the reference to the object in memory. Specifically l1 points to a list, when you call a method, the variable l1 isn't passed (that would be pass by reference), but the value of l1 is passed, this value is a reference to the same object. If you reassign the argument l with a different List, then the variable in the caller (l1) is unchanged.

特别是在您的示例中,List.subList 是基础列表上的视图.修改子列表(在您的代码中调用 clear())也会修改支持的原始列表.

Specifically in your example this is further compounded by the fact that List.subList is a view on the underlying list. Modifying the sublist (in your code calling clear()) will also modify the backing original list.

您的具体示例甚至包含在 API 文档中:

Your specific example is even included in the API documentation:

返回此列表中指定的 fromIndex(包含)和 toIndex(不包含)之间的部分的视图.(如果 fromIndex 和 toIndex 相等,则返回的列表为空.)返回的列表由此列表支持,因此返回列表中的非结构性更改会反映在此列表中,反之亦然.返回的列表支持此列表支持的所有可选列表操作.

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

此方法消除了对显式范围操作(数组通常存在的排序)的需要.通过传递子列表视图而不是整个列表,任何需要列表的操作都可以用作范围操作.例如,以下习语从列表中删除一系列元素:

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

 list.subList(from, to).clear();

这篇关于当我在 java 中使用链表时,它似乎不是“按值传递";再说了,谁能解释一下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆