Pass Parameter In Wrapper Object

JavaPassesByValue, but sometimes you want PassByReference.

Therefore: Wrap the parameter in a container object:

  class Wrapper
	{
	public int value;
	}

void incrementValue (Wrapper wrapper) { wrapper.value++; }

...

Wrapper wrapper = new Wrapper(); wrapper.value = 2; incrementValue (wrapper); System.out.println (wrapper.value);

3

However: This smells funny, so see AlternativesToPassByReference

Also, this increases the number of classes. This will increase download time if the application or applet is loaded across the network. One or two classes may not matter, but if you need a lot of wrapper classes, either use arrays or try to refactor your code to avoid by-reference parameters.

See also: PassParameterInArray


I don't understand this. It would only seem to apply to primitives -- Java passes objects by reference automatically, right? -- and if you're just want a primitive value, why not just return it? Perhaps a less-trivial example would be more instructive.

Just returning a primitive value does not work when you have two or more parameters. The example above, which wraps a primitive type, is practically identical to an example where one would wrap an object reference.

To answer the "Java passes objects by reference automatically, right?" question: There are two things to remember:

	# Java passes all parameters by value.
	# The passed value can be a reference to an object or a primitive type.


CategoryJava
EditText of this page (last edited July 7, 2004)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006