Another simple example of the power of collections.
- CREATE ARRAY AND POPULATE IT
- CREATE LIST AND COPY ARRAY CONTENTS TO IT
- CREATE SECOND LIST
- POPULATE IT
- DISPLAY CONTENTS
- COPY LIST 1 CONTENTS TO LIST 2
- 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