0
ArrayList<Integer> aList1=new ArrayList<Integer>();
ArrayList<Integer> aList2=new ArrayList<Integer>();
aList1.add(1);
aList2=aList1;
aList1.clear();

System.out.println(aList1.size());
System.out.println(aList2.size());

Why here both lists have size zero? As per my understanding aList1.size() should be 0 and aList2.size() should be 1.

008ak89
  • 325
  • 1
  • 3
  • 8
  • 1
    Read this post and it's answers... This will clear things up: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – ParkerHalo Aug 01 '18 at 12:26
  • 1
    See also: [How to copy a java.util.List into another java.util.List](https://stackoverflow.com/questions/14319732/how-to-copy-a-java-util-list-into-another-java-util-list) – OH GOD SPIDERS Aug 01 '18 at 12:28

1 Answers1

2

When you make an assign like this :

aList2 = aList1;

The aList2 will point to the same Memory address of aList1 for that when you change aList1 the first also changed.


Consider you have a list like this :

      +---+     +---+
O---> | 1 | --- | 2 |
      +---+     +---+

When you assign :

aList2 = aList1;

It will be like this :

                  +---+     +---+
      +--> L1---> | 1 | --- | 2 |
      |           +---+     +---+
      |
  L2--+

When you change L1 the

  aList1.clear();

the other list also will be affected

      +--> L1---> null
      |           
      |
  L2--+

to solve this issue you can use :

aList2 = new ArrayList<>(aList1);

This will return :

0
1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • I know how to solve the issue, I wanted to know the reason. – 008ak89 Aug 01 '18 at 12:28
  • 2
    I already said the reason @008ak89 did you read my answer? – Youcef LAIDANI Aug 01 '18 at 12:29
  • So why it is different for any class,Parent p1=new Parent(); Parent p2=p1; p1=null; System.out.println(p1); System.out.println(p2); – 008ak89 Aug 01 '18 at 12:38
  • @008ak89 what did you mean I don't get you? – Youcef LAIDANI Aug 01 '18 at 12:43
  • "The aList2 will point to the same Memory address of aList1" i.e. both the objects will be pointing to the same memory address, then why in this example p1 is null but p2 is having some reference. Parent p1=new Parent(); Parent p2=p1; p1=null; System.out.println(p1); System.out.println(p2); – 008ak89 Aug 01 '18 at 12:47
  • 1
    @008ak89 please read this https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Youcef LAIDANI Aug 01 '18 at 13:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177247/discussion-between-008ak89-and-ycf-l). – 008ak89 Aug 02 '18 at 04:39