Java List copy using Collections


Another simple piece of code that may come in handy, this code copies from one list to another using the Collectons method.

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

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


/// SIMPLE LIST COPY METHOD THAT 
/// 1 - CREATES CHARACTER ARRAY
/// 2 - COPYS CONTENTS OF ARRAY TO LIST1
/// 3 - DISLAYS CONTENTS
/// 4 - REVERSES CONTENTS
/// 5 - DISPLAYS REVERSED CONTENTS
/// 6 - CREATES ANOTHER CHARACTER ARRAY
/// 7 - COPYS CONTENTS OF ARRAY TO LIST2
/// 8 - AND FINALLY COPIES CONTENTS FROM LIST 1 TO LIST 2 
////////AND DIPLAYS CONTENTS OF LIST 2 //////////////////

class listCopy
{
public static void main(String args[])
{
Character[] newArray ={'P','J','C'};
List<Character> newList = Arrays.asList(newArray);


System.out.println("Before reverse : "+newList);
Collections.reverse(newList);

System.out.println("After reverse : "+newList);


///CREATE NEW ARRAY AND NEW LIST
Character[] newArray2 = new Character[3];
List<Character> newList2 = Arrays.asList(newArray);


//COPY FROM SOURCE = newList  to DESTINATION = newList2
Collections.copy(newList2,newList);
System.out.println("COPIED LIST : "+newList2);
}
}

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


Before reverse : [P, J, C]
After reverse : [C, J, P]
COPIED LIST : [C, J, P]


No comments:

Post a Comment