Why are these Java enums changing values? -
I have a problem creating a list of objects based on a condition at enum
. It seems that after completing the list, every item in the list is equal to the last item.
This is a classic matter of different contexts pointing to the same object, but I do not know how to avoid it:
While I have done everything while maintaining readability, The number of things I keep:
public square fu (digit [] array = new issue [2]; ArrayList & lt; foo> foozlets; foo () {array [0] = Digit Zero; Fuzzlets = New Arreelist & lt; Foo & gt; ();} Foo (Foo old, numeral number) {this.array = old.array; \\ This line is a problem, Or array should be called? Array [1] = number;} public static zero main (string [] args) {Foo f = new Foo (); System.out.println ("initial fu:"); println (f); f .listFoozlets ();} zero list for Foozlets () (for digit: digit.values ()) {if (k == digit. TWO || k == digit.five) {foozlets.add (new fu ( This, K)); System.out.println ("** Foozlet is being added"); Fu Fu = New Foo (this, K); Println (foo);}} System.out.println (" ** Foozlets ** list for "); (Fu Fu: Fuzletts) {System.out.println (foo);}} public string toString () {return array [0] .toString () +" "+ + Leading [1] .toString (); }} Output is: Initial Fu: Zero Zero ** Foozlet: {ZERO, ONE, TWO, THREE, FOUR, FIVE}
Being added ** two pairs ** Foozlet being added ** zero FIVE ** list of Foozlets ** zero five zero five
If someone can explain why Fu
list changes, and how can I create a list that does not change, I will be grateful.
Edit: OK, I see the problem is now really, in a very big program, I have a lot of array, and I have a new foo I want to keep old information on making I have changed this code that there is additional information to reflect that I want to keep. How can I complete it?
This is a small criminal:
Fu (Fu old, issue Number) {this.array = old.array; Array [0] = number; }
You are copying the reference to the old foo array, and then changing the values in that array.
Why do you do so even though there is an array of size 1 rather than just a Here is a small example: digit / <>? If you really want the array, you probably want to clone it instead of just copying the reference, but we can not really tell what the intention is.
value points {zero, one, two, three, four, five} public squares (numeric [] array = new digit [ 1]; Foo () {array = 0] = digit. Zoro;} fu (foo old, numeral number) {this.array = old.array; array [0] = number;} public string toString () {return array [0] .toString ();} Public static zero main (string [] args) {Foo f = new Foo (); Println (f); Fu other = new Foo (F, digit.one); Println (f) ;}}
Comments
Post a Comment