java - list value replaced when set value to the sam object -
list value replaced when set value list. please me .
public void testvalue(){ invintc1 = new arraylist<>(); invintc2 = new arraylist<>(); invintc invin = new invintc(); invin.setinvintckey("1234"); invin.setinvintcqty(1); // set value in here invintc1.add(invin); invintc invin2 = invintc1.get(0); invin2.setinvintcqty(5); // , when set value again, value invintc1 replaced 5 invintc2.add(invin); }
you have one object here - 1 instance of invintc.
the values in both array lists refer same object, changes made object visible via both lists.
as real world example, suppose write down home address on 2 pieces of paper, , give 1 piece of paper joe , 1 fred. joe goes , paints front door red... fred visits house. of course he'll see red front door. same thing happening in code.
if want 2 independent objects, need create 2 independent objects:
invintc invin = new invintc(); invin.setinvintckey("1234"); invin.setinvintcqty(1); invintc1.add(invin); invintc invin2 = new invintc(); // copy key 1 object other invin2.setinvintckey(invin.getinvtckey()); // set different quantity invin2.setinvintcqty(5); invintc2.add(invin); it's vitally important understand how objects , references work in java. suggest hold of book explains in detail.
(i'd encourage rethink names more friendly.)
Comments
Post a Comment