java - How do I pass a primitive data type by reference? -


how can pass primitive type reference in java? instance, how make int passed method modifiable?

there isn't way pass primitive directly reference in java.

a workaround instead pass reference instance of wrapper class, contains primitive member field. such wrapper class extremely simple write yourself:

public class intref { public int value; } 

but how pre-built wrapper classes, don't have write our own? ok:

the apache commons-lang mutable* classes:
advantages: performance single threaded use. completeness.
disadvantages: introduces third-party library dependency. no built-in concurrency controls.
representative classes: mutableboolean, mutablebyte, mutabledouble, mutablefloat, mutableint, mutablelong, mutableobject, mutableshort.

the java.util.concurrent.atomic atomic* classes:
advantages: part of standard java (1.5+) api. built-in concurrency controls.
disadvantages: small performance hit when used in single-threaded setting. missing direct support datatypes, e.g. there no atomicshort.
representative classes: atomicboolean, atomicinteger, atomiclong, , atomicreference.
note: user colind shows in answer, atomicreference can used approximate of missing classes, e.g. atomicshort.

length 1 primitive array
oscarryz's answer demonstrates using length 1 array "wrap" primitive value.
advantages: quick write. performant. no 3rd party library necessary.
disadvantages: little dirty. no built-in concurrency controls. results in code not (clearly) self-document: array in method signature there can pass multiple values? or here scaffolding pass-by-reference emulation?

also see
answers stackoverflow question "mutable boolean field in java".

my opinion
in java, should strive use above approaches sparingly or not @ all. in c common use function's return value relay status code (success/failure), while function's actual output relayed via 1 or more out-parameters. in java, best use exceptions instead of return codes. frees method return values used carrying actual method output -- design pattern java programmers find more natural out-parameters.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -