Web Development, SEO, Social Media, Software & Database Development
Java converting LinkedList to Array
From time to time you may need to convert your linkedlist back to array, this can be done with the .toArray method from the Linkedlist.
------------------- CODE ---------------------------------
import java.util.LinkedList;
import java.util.Arrays;
class list2Array
{
public static void main(String args[])
{
//CREATE ARRAY AND POPULATE IT
String names[] ={"Mark","Paul","James","Clair"};
//CREATE LINKEDLIST AND POPULATE IT WITH ABOVE ARRAY
LinkedList<String> nameList = new LinkedList<String>(Arrays.asList(names));
/// ADD NEW ITEM TO END OF LIST
nameList.add("Andy");
// ADD NEW ITEM TO START OF LIST
nameList.addFirst("Joe");
//NOW CONVERT THE LINKED LIST BACK TO ARRAY
names=nameList.toArray(new String[nameList.size()]);
for(String x: nameList)
System.out.println(x);
}
}
-----------------OUTPUT ----------------------------------
Joe
Mark
Paul
James
Clair
Andy
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment