kamikaze_pilot
kamikaze_pilot

Reputation: 14844

passing objects by value in 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

Upvotes: 1

Views: 9365

Answers (3)

Sweta
Sweta

Reputation: 11

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.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

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));

Upvotes: 1

Vijay Mathew
Vijay Mathew

Reputation: 27184

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.

Upvotes: 4

Related Questions