- HashSet底层是HashMap实现的,set的不可重复就是利用了map里面键对象的不可重复
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
JavaBean ,实体类 — 只有属性和get,set方法
一个对象对应一行记录,一个类对应一个表结构
一个map对象对应一行记录
Iterator
- boolbean hasNext() 判断是否有元素没有被遍历
- Object next() 返回游标当前位置的元素并将游标移动到下一个位置
- void remove() 删除游标左边的元素,在执行完next之后该操作只能执行一次
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
泛型(使用时只能使用引用类型)常见字母,类名后添加
- T Type表示类型
- K V 分别代表键值中的key,value
- E 代表Element
- ? 表示不确定的类型
泛型声明时不能使用在静态属性,静态方法上
接口中泛型字母只能使用在方法中,不能使用在全局常量中
泛型方法只能访问对象的信息,不能修改信息泛型通配符< ? > — 任意类型,如果没有明确,那么就是Object以及任意的Java类了
? extends E — 向下限定,E及其子类
? super E — 向上限定,E及其父类for,foreach,迭代器 循环遍历两重容器
ArrayList的toString:(直接打印ArrayList)
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
- TreeSet — 排序,唯一(红黑树) ,
自然排序(元素具备比较性) 自定义类实现compareTo接口(集合具备比较性)
比较器排序(匿名内部类 常用)
class people implements Comparable<people> {...}
Collection<people> ts = new TreeSet(new Comparator <people> (){
@Override
public int compare(people o1, people o2) {
return 0;
}
});
- Set set = map1.keySet() — 返回此地图中包含的键的Set视图。
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //唯一性
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
HashTable 和 HashMap(数组 + 链表 / 红黑树)
- Hashtable — 线程安全,效率低,不允许NULL值和null建
- HashMap — 线程不安全,效率高,允许NULL值和null建
Collection 与 Collections
- Collection是单列集合的顶层接口,有子接口List和Set
- Collections是针对集合操作的工具类,有对集合进行排序和二分查找的方法(都是静态方法)
- Collections.sort();
- Collections.reverse();
- Collections.shuffle(); 打乱顺序
- Collections.binarySearch(,);
可以使用接口类型存放集合的引用