Skip to content

Instantly share code, notes, and snippets.

@adaptives
Created July 28, 2011 06:13
Show Gist options
  • Save adaptives/1111060 to your computer and use it in GitHub Desktop.
Save adaptives/1111060 to your computer and use it in GitHub Desktop.
Using Lists in Java
package com.diycomputerscience;
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
/**
* This class explains the usage of Lists in Java
*/
public class JavaLists {
public static void main(String args[]) {
List<String> list = createArrayList();
accessElement(list);
removeElement(list);
}
private static List<String> createArrayList() {
// Create an ArrayList which can contain Strings and populate it
List<String> list = new ArrayList<String>();
list.add("Aamras");
list.add("Frooti");
list.add("Pepsi");
// Notice that this method returns a list and not an ArrayList. This allows
// us to change the list implementation and return another List type such as
// LinkedList if we so choose
return list;
}
private static void accessElement(List<String> list) {
// Access an element at a particular location
System.out.println("The 2nd element of the list is: " + list.get(1));
// Print all elements of the list
System.out.println("Printing all elements of the list");
for (String element : list) {
System.out.println(element);
}
}
private static void removeElement(List<String> list) {
//Let's remove the 3rd element from the list using the element's index
list.remove(2);
System.out.println("Removed 'Pepsi' from the list. New list contents: ");
System.out.println(list);
//Let's remove an element using the ListIterator interface
ListIterator<String> listIter = list.listIterator();
while(listIter.hasNext()) {
String element = listIter.next();
if(element.equals("Frooti")) {
System.out.println("Removed 'Frooti' from the list. New list contents: ");
listIter.remove();
}
}
System.out.println(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment