简体   繁体   English

在Java中按值传递对象

[英]passing objects by value in java

so suppose i have 所以假设我有

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

and I pass X into some parameter: 然后将X传递给一些参数:

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... 它将通过引用而不是值传递X,我不希望这样做。...类某物具有一个Arraylist类型的字段,该字段应该与自己不同,并且我不想遍历该死的arraylist并单独设置它只是为了实例化字段...

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 有没有一种方法可以轻松地使Java通过值而不是引用传递任何对象参数,而不必在我的所有对象上实现可克隆的接口,这很麻烦

As Java do not allow direct pointer manipulation, you cannot dereference a pointer. 由于Java不允许直接操作指针,因此无法取消引用指针。 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 ). 如果要防止修改传递的对象,则必须对其进行克隆或使其不可变(例如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. 因此,如果我们从C ++的意义上考虑通过引用 ,则“ Java具有通过引用”这样的语句是不准确的。

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. ArrayList的构造函数获取一个现有列表,读取其元素(无需修改!),然后将其添加到新的List中。

It actually passes X by value. 实际上,它按值传递X。 (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. (Something构造函数无法在调用代码中更改变量X。)X恰好是对ArrayList的引用,而不是ArrayList。 You could try: 您可以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM