《Java编程思想第四版》读后感:
文章分两部分:
一、List、Set、Map基本介绍
二、理解hashCode,和对hashMap的put和get源码分析。
一、List、Set、Map基本介绍
1、List和Set继承了Collection接口,而Map并不是。
2、图中虚线实心黑色箭头,是指可以通过某个方法得到所指向的接口。
例如:
ListIterator listIterator = list.listIterator();
Collection values = map.values();
3、ArrayList:保证元素按照规定的顺序排列,可以添加重复的数据。不是线程安全的,要保证线程安全建议使用Vector,在addElement()等方法添加了synchronized[’sɪŋkrənaɪzd] 。ArrayList的特点是提供了快速访问。
4、LinkedList在API中说明了是用双链表实现的高效率地在列表中部进行插入和删除操作,但是随机访问慢于ArrayList。
5、LinkedList和ArrayList都可以通过方法得到ListIterator.
ListIterator linkedListIterator = linkedList.listIterator();
ListIterator arrayListIterator1 = arrayList.listIterator();
利用它可在一个列表里朝两个方向遍历,同时插入和删除位于列表中部的元素(插入和删除建议使用LinkedList)
6、HashSet:HashSet里面的数据是无序不可重复的并且如果放入的是一些继承Object的类,你应该重写equals和hashCode方法。
如果是String、Integer等类则不需要,以为在源码中已经给你写好了。
7、TreeSet:TreeSet是有序和不可重复的。对于TreeSet大致可分为自然排序和Comparator进行排序。
从TreeSet的构造函数中可以看到:
// 默认构造函数。使用该构造函数,TreeSet中的元素按照自然排序进行排列。
TreeSet()
// 创建的TreeSet包含collection
TreeSet(Collection<? extends E> collection)
// 指定TreeSet的比较器
TreeSet(Comparator<? super E> comparator)
// 创建的TreeSet包含set
TreeSet(SortedSet<E> set)
- 自然排序:对于一些基本数据类型的包装类例如Integer,String等等。其实这些类里面都已经实现了Comparable接口。
- Comparator:如果我们在集合中添加的是我们自己写的类,那么就应该实现Comparator接口,并重写compareTo方法。
如果不实现这个接口会抛出
Exception in thread "main" java.lang.ClassCastException: com.example.MyType cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at com.example.Set2.main(Set2.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
class MyType implements Comparable {
private String name;