0

Let's say I have 3 ArrayList <Integer>.

The 1st AL is : [1,2,3,4].

The 2nd AL is : [5,6,7,8].

The 3rd AL is going to save all numbers from the other 2 AL, so it will be [1,2,3,4,5,6,7,8] or [5,6,7,8,1,2,3,4].

How to create a reference in memory from the 3rd AL to the 1st and 2nd, so that I don't need to create new objects for the 3rd list, just create a reference from memory cells of 3rd AL pointing to the 1st's and 2nd's AL objects.

tur1ng
  • 1,082
  • 1
  • 10
  • 24
  • 5
    Just add AL1 and AL2 to AL3. It doesn't make new instances of the elements, it just adds references to the same instances. [Ideone demo](http://ideone.com/jTqBAy). – Andy Turner Apr 22 '16 at 13:01
  • 1
    `AL1.addAll(AL2);` – Rabbit Guy Apr 22 '16 at 13:06
  • @AndyTurner You are correct, **and** `Integer` is *also* **imutable** and there is something special about [-128 to 127](http://stackoverflow.com/a/1700117/2970947). – Elliott Frisch Apr 22 '16 at 13:09
  • @ElliottFrisch it would be no different if it used `new Integer(0)` etc throughout. There is nothing special about the way `Integer` (or other immutable) instances are handled by `ArrayList`. – Andy Turner Apr 22 '16 at 13:10
  • @AndyTurner Sorry, I said you're correct; just adding reasons why OP's concerns are unjustified. – Elliott Frisch Apr 22 '16 at 13:12

1 Answers1

0
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1099,9872,3453));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(4765,9875,6564));
        List<Integer> list3 = new ArrayList<>();
        list3.addAll(list1);
        list3.addAll(list2);
        System.out.println(list3.get(0)==list1.get(0));