Java Collections.addAll simple example


Another simple example of the power of collections.


  1. CREATE ARRAY AND POPULATE IT
  2. CREATE LIST AND COPY ARRAY CONTENTS TO IT
  3. CREATE SECOND LIST
  4. POPULATE IT
  5. DISPLAY CONTENTS
  6. COPY LIST 1 CONTENTS TO LIST 2
  7. DISPLAY CONTENTS


------------------CODE-----------------

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;


class addAll
{
public static void main(String args[])
{
String[] stuff={"Apples","Lemons","Shoes","Pigs"};
List<String> list1 =Arrays.asList(stuff);


ArrayList<String> list2 = new ArrayList<String>();
list2.add("Facebook");
list2.add("Twitter");
list2.add("Youtube");
list2.add("LinkedIn");


// SHOW CONTENTS OF LIST 2 BEFORE ADDING STUFF
for(String x: list2)
System.out.printf("%s ",x);


///ADDS CONTENTS OF STUFF LIST TO THE LIST2 LIST

Collections.addAll(list2,stuff);

// SHOW CONTENTS OF LIST 2 AFTER ADDING STUFF
System.out.println();
for(String x: list2)
System.out.printf("%s ",x);

}
}

--------------OUTPUT-----------------------------


Facebook Twitter Youtube LinkedIn
Facebook Twitter Youtube LinkedIn Apples Lemons Shoes Pigs

No comments:

Post a Comment