import java.util.LinkedList; import java.util.List; public class ConvertLinkedListToArrayExample { public static void main(String[] args) { // create an LinkedList object List< string > list = new LinkedList< string >(); // Add elements to the list list.add("India"); list.add("Switzerland"); list.add("Italy"); list.add("France"); System.out.println("LinkedList contains..."); // display elements of LinkedList for (int index = 0; index < list.size(); index++) System.out.println(list.get(index)); /** * Object[] toArray() - Returns an Object class array containing all of * the elements in this list in the correct order.Note that we can't * explicitly cast the returned array to some other class type. **/ Object[] countries = list.toArray(); System.out.println("Content of array countries="); for (Object c : countries) { System.out.println(c); } /** * Object[] toArray(Object[] a) - Returns an array containing all of the * elements in this list in the correct order; the runtime type of the * returned array is that of the specified array. **/ String[] countries1 = list.toArray(new String[list.size()]); System.out.println("Content of array countries1="); for (String c : countries1) { System.out.println(c); } } }
The output is:
LinkedList contains...
India
Switzerland
Italy
France
Content of array countries=
India
Switzerland
Italy
France
Content of array countries1=
India
Switzerland
Italy
France
No comments:
Post a Comment