Vinod
Vinod

Reputation: 2311

How replace one list items with another in java?

I have two array lists, Can it possible to replace the one list items with the second list.

ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
a.add("testone");
a.add("testtwo");
a.add("testthree");
b.add("demoone");
b.add("demotwo");
System.out.println("List values are: "+ a);

Is there any way to replace the first list with the second list elements. So if I print first array list, it should print the following output

[demoone, demotwo] 

Upvotes: 0

Views: 1959

Answers (4)

Monil Singhal
Monil Singhal

Reputation: 29

So there are two ways to do this based on requirement.

  1. You need the list referenced by reference variable b to be available with the reference variable a. In this case the original list referenced by a is not required to be modified, just the reference variable a is being pointed to the second list (originally referenced by reference variable b).

    a = b;
    System.out.println("List values are: "+ a);
    
  2. You need the list referenced by reference variable a to have the items present in the list referenced by b. In this case, the actual list originally referenced by a has to be modified. This might be required when you are passing the list to a method which is supposed to modify the list.

    a.clear();
    a.addAll(b);
    System.out.println("List values are: "+ a);
    

Upvotes: 2

user2575725
user2575725

Reputation:

Option 1:

a = b; //copy same list reference

Option 2:

a.clear(); //clear all existing items
a.addAll(b); //copy all

Option 3:

a = (ArrayList<String>)b.clone(); //shallow copy

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

I guess you need:

a = b;
System.out.println("List values are: "+ a);

Upvotes: 3

Sarit Adhikari
Sarit Adhikari

Reputation: 1402

simplest way to do is assign list b to list a

a=b

Upvotes: 3

Related Questions