Collections

1. List

List is an interface

1.1 ArrayList

  • index

  • grow/shrink

  • allow duplicates

  • not synchronized

    ConcurrentModificationException : 不支持multi-thread.

//declare collection with interface, instantiate it with specific implementation
List<String> myArrayList = new ArrayList<String>();

myArrayList.add("yep!");
...
myArrayList.isEmpty();
myArrayList.toString();
myArrayList.remove(5);
myArrayList.remove("yep!");

1.2 LinkedList

  • no index

  • references to the next&pre element

  • Queue (interface) - FIFO

List<String> myLinedList = new LinkedList<String>();

myLinkedList.add("yep!");
...
myLinkedList.toString();
myLinkedList.remove(5);
myLinkedList.remove("yep!");

//traverse 1 : standard iterator
Iterator iter = myLinkedList.iterator();
while(itr.hasNext()) {
  System.out.print(itr.next());
}

//traverse 2 : for each loop
for(String letter : myLinkedList) {
  System.out.print(letter);
}

2. Set

Set is an interface

  • no duplicates

  • no index

2.1 HashSet

  • hashing

    translate value into "unique" memory location(address) and store that value in that address

  • does not maintain order

Set<Integer> myHashSet = new HashSet<Integer>();

myHashSet.add(5);
...
myHashSet.remove(5);
myHashSet.inEmpty();
myHashSet.clear();
myHashSet.contains(5);

2.2 TreeSet

  • maintain order( sorting )
Set<Integer> myTreeSet = new TreeSet<Integer>();

myTreeSet.add(5);
...
myTreeSet.remove(5);
myTreeSet.inEmpty();
myTreeSet.clear();
myTreeSet.contains(5);

//traverse in descending order
Iterator<Integer> iter = ((TreeSet<Integer>)myTreeSet).descendingIterator();
while(iter.hasNext()) {
    System.out.println(iter.next());
}

2.3 LinkedHashSet

  • maintainer order as adding

3. Map

Map is an interface

3.1 HashMap

  • put(Key, Value)
Map<String, List<String>> myHashMap = new HashMap<String, List<String>>();

myHashMap.put(... , ...);
...
myHashMap.remove(...);
myHashMap.containsKey(...);
myHashMap.containsValue(...);

//traverse K
for(String key : myHashMap.keySet()) {
  System.out.println(key);
}

//traverse V
for(List<String> value : myHashMap.values()) {
  for(String str : value) {
    System.out.println(str);
  }
}

//traverse both K&V : entry
for(Map.Entry<String, List<String> entry : myHashMap.entrySet()) {
  System.out.println(entry.getKey() + ":" + entry.getValue() );
}

results matching ""

    No results matching ""