Java基础学习 day_10 Set集合

Set

无序 无下标 不可重复

hashSet

存储结构:哈希表
判断重复的依据:hashCode和equals方法。
用的是hashMap,用key来存储元素。
存储过程:
(1)根据hashCode计算存储的位置,如果此位置没有元素,则添加。
(2)如果此位置有元素,再比较equals(),如果equals()相同,则拒绝添加。
所以说要重写hashCode()和equals();

hashtable:(本质数组+链表)
JDK1.7(数组+链表)
JDK1.8(数组+链表+红黑树)

system.identityHashCode();得到原始的HashCode值

LinkedHashSet

存储结构:哈希表
特点:有序,没有下标,不能重复
linked:链表保存添加元素的顺序。

TreeSet

存储结构:红黑树
特点:无序,无下标,不能重复
对元素进行排序
重复依据:Comparable接口中compareTo(),如果compareTo返回的是零,拒绝添加。
用的是TreeMap,用key存储元素。

如果用TreeSet,要实现Comparable的接口。

比较器:comparator
声明TreeSet集合时,可以用comparator的匿名类实现判断,比在类中重写compare()方法的优先级高。

TreeSet<String> treeSet=new TreeSet<>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        int n1=o1.length()-o2.length();
        int n2=o1.compareTo(o2);
        return n1==0? n2:n1;
    }
});

Map结构

在这里插入图片描述
添加:put(key,value);如果map中没有相同的键值,返回null,有相同的键值,替代该键值对应的值,并返回改制。
删除:remove(key);
清空:clear();
遍历:
1.keySet();

//遍历
Set<String> set = map.keySet();
for (String s : set) {
    System.out.println(s+"--->"+map.get(s));
}

2.entrySet();

//第二个遍历
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
    System.out.println(entry.getKey() + entry.getValue());
}

在这里插入图片描述

containsKey(key):是否包含key
contiansValue(value):是否包含value

HashMap

存储结构:哈希表
无序,无下标,key不可重复,value可以重复
重写hashCode()方法和equals()方法
并允许null的值和null键。

怎么计算位置的:拿hashCode的int值 高十六位和第十六位做异或,避免链表太长

LinkedHashMap

无下标,有序(按插入顺序)key不可重复,value可以重复

TreeMap

存储结构:红黑树
实现Comparable接口,重写compareTo()方法。

Properties(实现类)

存储的是属性名和属性值,只能存储字符串(key,value),没有泛型。而且和有关。
setProperty(key,value):添加元素
remove(key):删除元素
遍历:
1.keySet()
2.entrySet()
3.stringPropertyName():返回键值集合

getProperty(key):根据键值得到value

**System.getProperties()**确定当前的系统属性。

Properties properties = System.getProperties();
Set<String> strings = properties.stringPropertyNames();//变为集合
for (String string : strings) {
    System.out.println(properties.get(string));
}

总结

ArrayList():重写equals()方法
LinkedList():重写equals()方法
HashSet():重写hashCode()方法和equals()方法
LinkedSet():重写hashCode()方法和equals()方法
TreeSet():实现Comparable接口,重写compareTo()方法。
hashMap():重写hashCode()方法和equals()方法
TreeMap():实现Comparable接口,重写compareTo()方法。

重写了这些方法,才能进行添加和删除。要不会出现添加和删除的问题。

猜你喜欢

转载自blog.csdn.net/m0_45196258/article/details/107758499