package lecture.sample.collection;

import java.util.*;

/**
 * @author William Lee
 *
 *  
 */
public class CollectionSolution1 {


	public static void main(String[] args) {
		
		// The abstract collection interface
		java.util.Collection xCollection;
		
		// available abstract data type in java.util.*
		Set xSet;						// a collection of unordered non-duplicate elements
		List xList;						// an ordered list
		Map xMap;						// a list of (key, value) pair 
		
		// further useful abstract data type extending the above interfaces 
		SortedSet xSortedSet;		// a sorted set
		SortedMap xSortedMap;		// a sorted map 
		
		// other collection or collection-like classes
		Stack xStack;					// a FILO list
		BitSet xBitSet;					// a set of bits
		
		// How do we instantiate abstract collection?
		
		xMap = new HashMap();		// a hashed key map
		xSet = new HashSet();		// set using hash to determine uniqueness
		xList = new LinkedList();	// a singly linked list
		xSortedMap = new TreeMap();	// use binary sort
		
		// adding/removing items to/from collection
		Collection xSomeCollection = xSet;
		
		xSomeCollection.add("element one");
		xSomeCollection.add("element two");
		
		xList.add("list element one");
		xList.add("list element two");
		
		xMap.put("key1", "value1");
		xMap.put("key2", "value2");
		
		
		// retrieving items from collections
		String xZerothElement = (String)xList.get(0);
				
		Iterator xIterator = xList.iterator();
		while(xIterator.hasNext()){
			Object xAnObject = xIterator.next();		
			
			// examine the object here
			System.out.println(xAnObject);

			// removing an object like this?
			xList.remove(xAnObject);			

			// WRONG! Should use Iterator.remove();
			xIterator.remove();
		}
		
		
		// using Comparator for sorted collections
		xSortedSet = new TreeSet(new Comparator() {
			/**
			 * @see java.util.Comparator#compare(Object, Object)
			 */
			public int compare(Object o1, Object o2) {
				return 0;
			}

			/**
			 * @see java.util.Comparator#equals(Object)
			 */
			public boolean equals(Object obj) {
				return false;
			}
		});		
		
		// the Collections and Arrays helper classes
		
		Collections.binarySearch(xList, "hello");
		
		xList = Arrays.asList(new String[]{"a", "b", "c"});	
		
		
		// thread safety of collections
		List xThreadSafeList = Collections.synchronizedList(xList);
		synchronized(xThreadSafeList){
			// manipulate the list here while iterating
			Iterator xAnotherIterator = xThreadSafeList.iterator();
			while(xAnotherIterator.hasNext()){
				// do something with the list...	
			}	
		}		
		
	}
}