文章目录
1.集合和数组的区别?
A:长度区别
数组固定
集合可变
B:内容区别
数组可以是基本类型,也可以是引用类型
集合只能是引用类型
C:元素内容
数组只能存储同一种类型
集合可以存储不同类型(其实集合一般存储的也是同一种类型)
2. Collection特点
3.Collection和Map接口
Java集合中List,Set以及Map等集合体系详解(史上最全)
- List , Set, Map都是接口,前两个继承至Collection接口,Map为独立接口
Set
下有HashSet,LinkedHashSet,TreeSetList
下有ArrayList,Vector,LinkedListCollection
接口下还有个Queue接口,有PriorityQueue类Map
下有Hashtable,LinkedHashMap,HashMap,TreeMap
4. TreeSet, LinkedHashSet and HashSet 的区别
TreeSet的主要功能用于排序
LinkedHashSet的主要功能用于保证FIFO即有序的集合(先进先出)
HashSet只是通用的存储数据的集合
5. Collection和Collections的区别
Collection 是单列集合的顶层接口,有两个子接口List和Set
Collections 是针对集合进行操作的工具类,可以对集合进行排序和查找等,都是静态方法
6. HashSet保证元素唯一性
6.1 原理
class HashSet implements Set {
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) { //e=hello,world
return map.put(e, PRESENT)==null;
}
}
class HashMap implements Map {
public V put(K key, V value) { //key=e=hello,world
//看哈希表是否为空,如果空,就开辟空间
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//判断对象是否为null
if (key == null)
return putForNullKey(value);
int hash = hash(key); //和对象的hashCode()方法相关
//在哈希表中查找hash值
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
//这次的e其实是第一次的world
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//判断
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
//走这里其实是没有添加元素
}
}
modCount++;
addEntry(hash, key, value, i); //把元素添加
return null;
}
transient int hashSeed = 0;
final int hash(Object k) { //k=key=e=hello,
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode(); //这里调用的是对象的hashCode()方法
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}
观察源码可知,hashset实际上使用hashmap的put方法,关键比较:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
add方法底层主要依赖两个方法:hashCode()
和equlas()
。
先判断hashCode()值是否相同:
- 相同:继续判断equlas()方法。
– true:重复,不添加
– false:不重复,添加 - 不相同:直接添加
6.2 相同的字符串只存储一个
String类重写了hashCode()和equals()方法,所以,它就可以把内容相同的字符串去掉。只留下一个。
6.3 相同的自定义对象只存储一个
自定义类没有重写这两个方法,默认使用的Object()。一般来说不相同,默认会存储。故需要重写。
public class Person {
private String name;
private Integer age;
public Person(String name,Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(this == obj){//地址相同
return true;
}
if (!(obj instanceof Person)) {//是否是当前类的实例
return false;
}
Person s = (Person)obj;//是当前类的实例额,再继续比较属性
return this.name.equals(s.name)&& this.age == s.age;
}
@Override
public int hashCode() {
// 引用类型使用hashCode(),整型直接使用
return this.name.hashCode()+this.age;
}
}
7. TreeSet实现元素排序
7.1 原理
class TreeMap implements NavigableMap {
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();
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;
}
}
class TreeSet implements Set {
private transient NavigableMap<E,Object> m;
public TreeSet() {
this(new TreeMap<E,Object>());
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
}
通过观察TreeSet的add()方法,我们知道最终要看TreeMap的put()方法。
真正的比较是依赖于元素的compareTo()方法,而这个方法是定义在 Comparable里面的。
所以,你要想重写该方法,就必须是先实现 Comparable接口。这个接口表示的就是自然排序。
7.2 自然排序
常见的包装类型:已实现Comparable接口,可以进行自然排序;
自定义类:需要自己实现Comparable接口。
public class Student implements Comparable<Student> {
@Override
public int compareTo(Student s) {
// return 0; 指添加第一个元素
// return 1; 顺序
// return -1; 逆序
// 这里返回什么,其实应该根据我的排序规则来做
// 按照年龄排序,主要条件
int num = this.age - s.age; // 大于0,升序
// 次要条件
// 年龄相同的时候,还得去看姓名是否也相同
// 如果年龄和姓名都相同,才是同一个元素
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
7.3 比较器排序
需要构造器的实现类作为集合对象构造函数的参数。可以使用匿名内部类。
创建集合对象:
TreeSet<Student> ts = new TreeSet<Student>(); //自然排序
public TreeSet(Comparator comparator) //比较器排序
TreeSet<Student> ts = new TreeSet<Student>(new MyComparator()); // 需要使用带比较器的构造方法
定义构造器是实现类:
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
// 姓名长度
int num = s1.getName().length() - s2.getName().length();
// 姓名内容
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
// 年龄
int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;
return num3;
}
}
8. Map集合的遍历
(1)键找值
(2)键值对对象找键和值
Map<String,String> hm = new HashMap<String,String>();
hm.put("it002","hello");
hm.put("it003","world");
hm.put("it001","java");
//方式1 键找值
Set<String> set = hm.keySet();
for(String key : set) {
String value = hm.get(key);
System.out.println(key+"---"+value);
}
//方式2 键值对对象找键和值
Set<Map.Entry<String,String>> set2 = hm.entrySet();
for(Map.Entry<String,String> me : set2) {
String key = me.getKey();
String value = me.getValue();
System.out.println(key+"---"+value);
}
9.Hashtable和HashMap的区别
- Hashtable:线程安全,效率低。不允许null键和null值
- HashMap:线程不安全,效率高。允许null键和null值