6

I have two array list with different size. How to Replace from this:

ArrayList<String> s = new ArrayList<String>();
ArrayList<String> f = new ArrayList<String>();
        s.add("Nepal");
        s.add("Korea");
        s.add("Sri Lanka");
        s.add("India");
        s.add("Pakistan");
        s.add("China");
        s.add("Australia");
        s.add("Bhutan");

        f.add("London");
        f.add("New York");
        f.add("Mumbai");
        f.add("sydeny");
for(int i=0;i<s.size();i++){
           // Collections.copy(f, s);
            f.addAll(s);
            Log.d("TAG", "Sources---" + s.get(i));
           Log.d("TAG", "Dest---" + f.get(i));
        }

I have try both this. but not replace only append or copy from the existing array list. My aim is totally replace original array to new arraylist.

4 Answers 4

19

You may do clear() first and then do addAll(s);

After clear() your arraylist will be empty.

EDIT:

As @Luggi commented, clear() will not be good option if list is big, instead simply point your f reference to new ArrayList with collection as parameter: Example:

f = new ArrayList(s);
Sign up to request clarification or add additional context in comments.

1 Comment

Or even easier: f = new ArrayList(s);. Note that clearing a list with a big amount of elements (like 10k or more) performs slower than letting the GC doing its work.
2

enter link description hereenter link description hereYou can do this in many ways

  1. First clear then add all

    f.clear();
    f.addAll(S);

  2. By first way all element copy from one list to another list if you want that both the list are same and manipulation in one list reflects in another list then you can point both on the same list like

    f = s;

  3. By intializing new list by adding all element into a new list.

    f = new ArrayList(s);

Comments

1
    ArrayList<String> s = new ArrayList<String>();
    ArrayList<String> f = new ArrayList<String>();

    s.add("Nepal");
    s.add("Korea");
    s.add("Sri Lanka");
    s.add("India");
    s.add("Pakistan");
    s.add("China");
    s.add("Australia");
    s.add("Bhutan");

    f.add("London");
    f.add("New York");
    f.add("Mumbai");
    f.add("sydeny");

    f.clear();
    f.addAll(s);

If you want to add elements in f to s following will work

    s.addAll(f);

That's all. Why you use for loop in your code?

Comments

1

You can try this out:

First add all elements from s to f

f.addAll(s);

Then retain only elements in f that are present in s

f.retainAll(s);

Comments

Your Answer

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