list.add("red");
list.add("pink");
list.add("green");
list.addFirst("cyan");
list.addLast("blue");
// Create an iterator to step through the list
System.out.println("Iterating forward");
ListIterator iterator = list.listIterator();
while(iterator.hasNext()) {
// get an item
Object object = iterator.next();
if(object instanceof String) {
System.out.println("colour is "+(String)object);
}
}
System.out.println(" ");
System.out.println("Iterating backwards");
while(iterator.hasPrevious()) {
// get an item
Object object = iterator.previous();
if(object instanceof String) {
System.out.println("colour is "+(String)object);
}
}
System.out.println("Sort the list");
// Here we use a 'sort' algorithm that can sort any type
// of collection (of which linked lists are one).
Collections.sort(list);
System.out.println("Iterating forward through sorted list");
while(iterator.hasNext()) {
// get an item
Object object = iterator.next();
if(object instanceof String) {
System.out.println("colour is "+(String)object);
}
}
System.out.println("Removing the 2nd colour");
// Remove the 2nd entry
list.subList(2,3).clear();
// Step through the list in an alternative way
for(int i=0;i<list.size();i++)
System.out.println("Colour "+(String)list.get(i));