java中按值传递对象

发布于 2024-10-18 12:20:43 字数 356 浏览 1 评论 0原文

所以假设我已经将

ArrayList<E> X = new ArrayList<E>();

X 传递给了某个参数:

Something Y = new Something(X);

它将通过引用而不是通过值传递 X,而我不想要这个....class Something 有一个 Arraylist 类型的字段,该字段应该与其自身不同,并且我不想遍历该死的数组列表并单独设置它只是为了实例化该字段...

有没有一种方法可以轻松地使 Java 按值而不是引用传递任何对象参数,而不必在其上实现可克隆接口我所有的东西都是令人痛苦的

so suppose i have

ArrayList<E> X = new ArrayList<E>();

and I pass X into some parameter:

Something Y = new Something(X);

it will pass X by reference rather than by value and I don't want this....class Something has a field with Arraylist type that is supposed to be distinct to itself and I don't want to go and iterate through the damn arraylist and set it individually just to instantiate the field...

is there a way to easily make Java pass any object parameters by value rather than reference without having have to implement cloneable interface on all my objects which is a pain in the butt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

驱逐舰岛风号 2024-10-25 12:20:43

由于 Java 不允许直接操作指针,因此无法取消引用指针。你必须忍受参考。如果你想防止传递的对象被修改,你必须克隆它或使其不可变(如String)。另请记住,对象引用是按值传递的。因此,如果我们采用 C++ 意义上的“按引用传递”,那么“Java 具有按引用传递”之类的语句并不准确。

As Java do not allow direct pointer manipulation, you cannot dereference a pointer. You have to live with references. If you want to prevent the passed object from being modified, you have to clone it or make it immutable (like String). Also keep in mind that object references are passed-by-value. So statements like "Java has pass-by-reference" is not exact, if we take pass-by-reference in the C++ sense.

西瓜 2024-10-25 12:20:43

它实际上按值传递 X。 (Something 构造函数无法更改调用代码中的变量 X。)X 恰好是对 ArrayList 的引用,而不是 ArrayList。你可以尝试:

Something Y = new Something(new ArrayList<E>(X));

It actually passes X by value. (The Something constructor can't change the variable X in the calling code.) X happens to be a reference to an ArrayList, not an ArrayList. You could try:

Something Y = new Something(new ArrayList<E>(X));
烟凡古楼 2024-10-25 12:20:43

您可以传递一个不可修改的列表,而不是每次都创建一个新对象。该列表是只读的,如果用户想要进行任何修改,则必须创建另一个列表。

List unmodifiableList = Collections.unmodifiableList(list);
List newList = new ArrayList(unmodifiableList);
Collections.sort(newList);

ArrayList 的构造函数采用现有列表,读取其元素(不修改它们!),并将它们添加到新列表中。

Instead of creating a new object everytime you can pass an unmodifiable list. This list is read-only and the user has to create another list if he wants to make any modification.

List unmodifiableList = Collections.unmodifiableList(list);
List newList = new ArrayList(unmodifiableList);
Collections.sort(newList);

The constructor of ArrayList takes an existing list, reads its elements (without modifying them!), and adds them to the new List.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文