Collections:
A collection (container) is an object that groups multiple elements into a single unit.
TreeSet: Keeps the elements sorted and prevents duplicates.Use red-black tree.
HashSet: Prevents duplicates.
LinkedList: Better performance for insertion and deletion
HashMap: Store name/value pairs. No duplicate keys. Can have duplicate values.
LinkedHashMap: Remember the order elements inserted.
Map is not a true collection.
Use Set /List/Map as the reference type instead of implementation types.
Set: prevent duplicates.
HashSet: hashtable.
TreeSet: Keep the elements sorted. Use red-black tree.
LinkedHashSet: Keep insertion order.
List:
ArrayList
LinkedList: Better performance for insertion and deletion
Vector
Deque: (deck)
Implement both stack and queue.
Map:
TreeMap:
HashMap:
LinkedHashMap:
HashTable:
1.hashMap去掉了HashTable 的contains方法,但是加上了containsValue()和containsKey()方法。
2.hashTable同步的,而HashMap是非同步的,效率上逼hashTable要高。
3.hashMap允许空键值,而hashTable不允许。
Ordering for sort:
Class | Natural Ordering |
---|---|
Byte | Signed numerical |
Character | Unsigned numerical |
Long | Signed numerical |
Integer | Signed numerical |
Short | Signed numerical |
Double | Signed numerical |
Float | Signed numerical |
BigInteger | Signed numerical |
BigDecimal | Signed numerical |
Boolean | Boolean.FALSE < Boolean.TRUE |
File | System-dependent lexicographic on path name |
String | Lexicographic |
Date | Chronological |
CollationKey | Locale-specific lexicographic |
1. public static <T extends Comparable<? super T>> void sort(List<T> list)
sort() method only takes comparable objects. T must be comparable. Implement Comparable interface.
2. public static <T> void sort(List<T> list, Comparator<? super T> c)
Use custom Comparator.
Generics: for type-safe collections
Generic Method:
public <T extends Animal> void takeThing(ArrayList<T> list)
HashSet 首先判断hashcode是否一致,利用hashcode产生数组下标。如果hashcode一致(可能是冲突),则调用equals()判断reference是否一样。
a.equals(b) implies a.hashCode()==b.hashCode(). Not verse.
If you override equals(), you must override hashcode().
Polymorphism:
public void takeAnimals(Animals[] animals); // can take subclass of Animal as arguments.
public void takeAnimals(ArrayList<Animal> animals); // can take only take Animal class.
To avoid adding wrong type to the ArrayList, use wildcards:
public <T extends Animal> void takeThing(ArrayList<T> list)
public void takeThing(ArrayList<? extends Animal> list)