Web Development, SEO, Social Media, Software & Database Development
Java LinkList Methods Tutorial
A basic example on how to use LinkList and ListIterator. We use 3 methods to display contents, remove items and reverse contents of the list.
--------------------CODE-------------------------------
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
class newLists
{
public static void main(String args[])
{
String names[]={"Paul","James","Sam","Clair","George","June"};
List<String> namelist= new LinkedList<String>();
//POPULATE LIST FROM ARRAY
for(String x:names)
namelist.add(x);
//DISPLAY CONTENTS OF LIST
printMe(namelist);
System.out.println("\n\nREMOVED ITEM LIST");
RemoveStuff(namelist,2,4);
printMe(namelist);
System.out.println("\n\nREVERSED ITEM LIST");
ReverseList(namelist);
}
//////////////////PRINT ME METHOD////////////////////////
private static void printMe(List<String> passedList)
{
for(String x: passedList)
System.out.printf("%s ",x);
}
//////////////////REMOVE STUFF METHOD/////////////////////
private static void RemoveStuff(List<String> passedList, int from, int to)
{
passedList.subList(from,to).clear(); //REMOVE PART OF LIST
}
//////////////////REVERSE LIST METHOD/////////////////////
private static void ReverseList (List<String> passedList)
{
/// PASS CONTENTS TO ITERATOR
ListIterator x = passedList.listIterator(passedList.size());
///CYCLE THROUGH THE ITERATOR WHILE CONDITION IS TRUE
while(x.hasPrevious())
{
System.out.printf("%s ",x.previous());
}
}
}
----------------------------------------------OUTPUT----------------------------------
Paul James Sam Clair George June
REMOVED ITEM LIST
Paul James George June
REVERSED ITEM LIST
June George James Paul
Labels:
Java,
LinkList,
ListIterator
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment