Does a Java "reference object" exist? -


sometimes pass immutable object method , change value inside of method or assign object parameter reference (example 1). or assign inside of anonymous inner class object final local variable (example 2). because of these cases not possible, use atomic(integer|long...) class or list (which bad, because list can contain multiple objects) purpose. alternatively, create class holds object , allows changing object:

public class referenceexample {      public static void main(string[] args) {         final reference<string> string = new reference<>("a");         // example 1:         method(string);          // example 2:         new thread() {             @override             public void run() {                 string.set("c");             };         }.start();     }      public static void method(reference<string> string) {         string.set("b");     }      private static class reference<t> {         private t value;          public reference() {}          public reference(t value) {             this.value = value;         }          public t get() {             return value;         }          public void set(t value) {             this.value = value;         }     }  } 

i wondering if such class exists in java or common library (e.g. in apache common project)? if not, there other solutions these problems?

you've found main solution, other 2 common approaches are

  • atomicreference, looks you've found
  • a single-element array, acts more or less mutable reference

that said, can find ways around need:

  • return (potentially different) reference method
  • implement method inside class contains mutable reference field, more appropriate anyway

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -