list value replaced when set value to the sam object

list value replaced when I set value to another list. please help me .

public void testValue(){
        invInTc1 = new ArrayList<>();
        invInTc2 = new ArrayList<>();

        InvInTc invIn = new InvInTc();
        invIn.setInvInTcKey("1234");
        invIn.setInvInTcQty(1); // I set value in here
        invInTc1.add(invIn);

        InvInTc invIn2 = invInTc1.get(0);
        invIn2.setInvInTcQty(5); // and when I set value again, value invInTc1 is replaced to 5
        invInTc2.add(invIn);
    }

Answers


You have one object here - one instance of InvInTc.

The values in both array lists refer to the same object, so changes made to that object will be visible via both lists.

As a real world example, suppose I write down my home address on two pieces of paper, and give one piece of paper to Joe and one to Fred. Joe goes and paints my front door red... then Fred visits my house. Of course he'll see a red front door. Exactly the same thing is happening in your code.

If you want two independent objects, you need to create two independent objects:

InvInTc invIn = new InvInTc();
invIn.setInvInTcKey("1234");
invIn.setInvInTcQty(1);
invInTc1.add(invIn);

InvInTc invIn2 = new InvInTc();
// Copy the key from one object to the other
invIn2.setInvInTcKey(invIn.getInvTcKey());
// But set a different quantity
invIn2.setInvInTcQty(5);
invInTc2.add(invIn);

It's vitally important that you understand how objects and references work in Java. I strongly suggest you get hold of a good book which explains it in detail.

(I'd also encourage you to rethink your names to be more friendly.)


Need Your Help

Erlang 'record' explanation

erlang records double-quotes

I was exploring the source code here:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.