4

So the below method I'm aware causes both variables to point to the same object, but if I did want to find the simplest method to has ArrayList s2 exactly the same as s1, how would I do this?

public static void main(String[] args) {

        ArrayList<String> s1 = new ArrayList<String>();
        for (int i = 1; i <= 3; i++) {
            s1.add(""+i);
        }
        ArrayList<String> s2 = s1;

    }
1
  • 1
    Note that you're doing an unnecessary String concatenation on the line in your for loop. Maybe the JVM will optimize that out, but I'd use Integer.toString(i) instead of ""+i to get the String representation of an int. Commented May 5, 2012 at 0:07

1 Answer 1

5

You should create s2 with s1 as parameter.

public static void main(String[] args) {

    ArrayList<String> s1 = new ArrayList<String>();
    for (int i = 1; i <= 3; i++) {
        s1.add(""+i);
    }
    ArrayList<String> s2 = new ArrayList<String>(s1);

}
Sign up to request clarification or add additional context in comments.

4 Comments

Worth mentioning that while you now have two references to different lists, the references inside those lists are the same, so changes to objects stored in one will affect the other. Not an issue when working with Strings (as they're immutable), but a general point to bear in mind when working with lists of other types of object.
@LuiggiMendoza's solution is also how I would do it, but you could also use s2.addAll(s1) or Collections.copy(s1, s2) after creating a new empty ArrayList<String>. The Collections and Arrays classes have a lot of other utility methods that you might want to review, because they'll come in handy at some point.
@rob I wasn't improving his code, just showing the easiest way to get a new ArrayList<String> that contains the same data that the s1 ArrayList. Yes, I agree that there are other ways to do the task in hand, just showing one of the many ways :)
@LuiggiMendoza Yes, I understood that. :) I wanted to mention the other alternatives but didn't think it warranted a separate answer since yours was good. I also wanted to introduce Tim to the Collections and Arrays classes, because every Java programmer should know about those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.