Java Collections
Classes extends Collection Interface are : Set, List, SortedSet. Vector and ArrayList are classes implemented collection interfaces.
When to use ArrayList, Vector or LinkedList ?
Vector is an old collection class that acts like a growable array, but can store heterogenous data elements. common methods are: add(object), remove(object), removeAll(), addAll() , contains(object), size(), setElementAt(object, index)
LinkedList is preferred than ArrayList when there is a frequent need to add and remove elements in the middle of the list, ArrayList is preferred when there is a need to randomly access the element in the list. get(index), set(index, object)
List has Iterator, which can be used to traverse list in order or reverse order, however, when removing element from list, it is best to have following code:
while (Listerator<String> ls = List<String> mylists.listrator(); Is.hasnext() )
String a = ls.next();
if (a.equals("a")) {
ls.remove(a);
}
For an example on how to use ListIterator, visit
http://www.java-samples.com/showtutorial.php?tutorialid=235
Note: if you put Listerator outside of while loop, when removing object from list, it will throw concurrentModifyException
Sorting of the collection elements:
Collection.sort(list) or Collection.sort(list, comparator)
Comparable interface:
public interface Comparable<T> { public int compareTo(T o); }
in Summary if you want to sort based on natural order or object then use Comparable in Java and if you want to sort on some other attribute of object
then Comparator in Java is the way to go
public class PersonSortByPerson_ID implements Comparator{
public int compare(Person o1, Person o2) {
return o1.getPersonId() - o2.getPersonId();
}
}
Read more:http://docs.oracle.com/javase/tutorial/collections/interfaces/order.htmlRead more: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz1z1CyRoUzRead more: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz1z1BkQdds
Stack (FILO)
Queue(FIFO)
For more details, visit
http://java.sun.com/developer/onlineTraining/collections/Collection.html#VectorAndStackClasses
http://tutorials.jenkov.com/java-collections/navigableset.html