This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Mutable versus Immutable Objects
Posted by Bill Venners on April 23, 2000 at 8:07 PM
> Hi all, > with the following attempt to transfer a program I failed. The Java program prints 'null', not 33. Is there a way, which leads to the correct result? But I do not mean programs, which int as return value supplies or which int a into an array of the length one pack. That already occurred to me. > If there is no solution: Why may one make something in Java with arrays, what is forbidden with normal objects? > Best greetings Lutz
> /************ C code ************************ > int x; > void subprog(int* a) > { > *a = 33; > return; > } > void main(void) > { > subprog(&x); > printf("%d\n", x); > } > ************* Faulty Java translation ******/ > public class Stupid > { > static Integer x; > static public void a(Integer y) > { > y = new Integer(33); > } > public static void main(String[] args) > { > a(x); > System.out.println(x); > } > } To your question: If there is no solution: Why may one make something in Java with arrays, what is forbidden with normal objects? Class Integer happens to be immutable. Once it is created with a value, it can't change. Arrays are always mutable. You can easily create a class that is mutable that allows you to do what you want, such as: class MutableInteger { private int val; MutableInteger(int val) { this.val = val; } int getVal() { return val; } void setVal(int newVal) { val = newVal; } }
Kind of an ugly class because it is so data-oriented, but I believe that should answer your question. bv
Replies:
|