-2

Hi I was wondering if I could assign a ArrayList to another ArrayList (like a pointer?) in Java.

Here is a example to illustrate my point

public class FooBar
{
    boolean Foo = true;
    public ArrayList<String> listA = new ArrayList<String>();
    public ArrayList<String> listB = new ArrayList<String>();

    public void Bar()
    {
        ArrayList<String> whichList;

        if(Foo)
            whichList = listA;
        else
            whichList = listB;

        for( String words : whichList )
        {
            // ...
        }   
    }   
}

Would this work?

  • It would be far more educational for you to just try this and see what happens. You could also use this as an opportunity to learn how to step through code in your IDE debugger. A willingness to experiment is a fundamental requirement of being a software developer. – Jim Garrison Mar 16 '16 at 06:14
  • Yes @JimGarrison is right! – Alok Gupta Mar 16 '16 at 06:15
  • Please check http://stackoverflow.com/questions/8441664/how-do-i-copy-the-contents-of-one-arraylist-into-another – Aman Sachan Mar 16 '16 at 06:21

2 Answers2

1

Of course it is possible but you have to think : what is the reason I am willing to do that?

If you think that the changes made via the new reference will not affect the other list, it's not correct.

If you want to manipulate the data without having to change the original list, the next will be interesting for you

whichList = new ArrayList<>(listA);

This will create a new object on the heap, with exactly the same data as in the original list and the changes will not affect the latter.


Other option, if you're just using the lists in your enhanced for loop, you can do the following, without having to use an intermediate list

public void Bar() {
    for (String s : foo ? listA : listB) {
        // doStuff
    }
}

The ternary operator helps you to evaluate the boolean value of foo. If it's true, we'll be looping through listA, if false through listB

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
0

yes, it work.

     whichList = listA;

After this statement, whichList and listA will point to the same memory unit.

You should take some more research.

Antony Dao
  • 425
  • 2
  • 14