Section 16 Collections and Generics

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:

Classes Implementing Comparable
ClassNatural Ordering
ByteSigned numerical
CharacterUnsigned numerical
LongSigned numerical
IntegerSigned numerical
ShortSigned numerical
DoubleSigned numerical
FloatSigned numerical
BigIntegerSigned numerical
BigDecimalSigned numerical
BooleanBoolean.FALSE < Boolean.TRUE
FileSystem-dependent lexicographic on path name
StringLexicographic
DateChronological
CollationKeyLocale-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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值