哪些网站是做免费推广的,摄影网站模版,东至网站定制,溧阳市住房和城乡建设局网站目录 1. Map和Set2. Map的使用3. Set的使用 1. Map和Set
Java中#xff0c;Map和Set是两个接口#xff0c;TreeSet、HashSet这两个类实现了Set接口#xff0c;TreeMap、HashMap这两个类实现了Map接口。
带Tree的这两个类#xff08;TreeSet、TreeMap#xff09;底层的数… 目录 1. Map和Set2. Map的使用3. Set的使用 1. Map和Set
Java中Map和Set是两个接口TreeSet、HashSet这两个类实现了Set接口TreeMap、HashMap这两个类实现了Map接口。
带Tree的这两个类TreeSet、TreeMap底层的数据结构是一棵红黑树一棵特殊的二叉搜索树带Map的这两个类HashSet、HashMap底层的数据结构是哈系桶
2. Map的使用
Map中常用的方法
方法作用V get(Object Key)返回key的valueV getOrDefault(Object key,V defaultValue)返回key的value,key不存在则返回默认值V put(K key,V value)设置key对应的value/插入一个新的键值对V remove(Object key)删除key对应的映射关系Set K keySet()返回所有的keyCollection V values()返回所有的valueSetMap.EntryK,V entrySet()返回boolean containKey(Object key)判断是否包含keyboolean containValue(Object value)判断是否包含value
Map.EntryK,V中的方法
方法说明K getKey()返回keyV getValue()返回Entry的valueV setValue(V value)将原来的value替换为指定的value
举个例子~~
public static void main(String[] args) {MapInteger, String map new TreeMap();//new HashMap也是一样的map.put(1, ZhangSan);map.put(2, LiSi);map.put(3, WangWu);//获取所有的key,返回值是SetKSetInteger set map.keySet();System.out.println(获取所有的key: set);System.out.println(-------------);//获取所有的valuesCollectionString collections map.values();System.out.println(获取所有的value collections);System.out.println(-------------);//获取所有的key和valuesSetMap.EntryInteger, String entries map.entrySet();System.out.println(获取所有的key和value entries);System.out.println(-------------);//key不能重复,value可以重复System.out.println(使用Map.EntryInteger, String中的setValue替换前);//for (Map.EntryInteger, String entry : entries) {System.out.println(entry.getKey() entry.getValue());}for (Map.EntryInteger, String entry : entries) {entry.setValue(111111);}System.out.println(替换后);for (Map.EntryInteger, String entry : entries) {System.out.println(entry.getKey() entry.getValue());}
}输出结果
注意事项
1、Map存储的是Key-Value结构的键值对key是唯一的不能重复value可以重复2、插入新的键值对时如果key重复了会更新key对应的value的值3、TreeMap插入的键值对key不能为空value可以为空HashMap插入的键值对key和value都可以为空4、Map中的key想要修改只能先删除再重新插入
3. Set的使用
与Map不同的是Set只存储key不存储value
常用的方法
方法说明boolean add()添加元素重复的元素不会添加成功void clear()清空整个集合boolean contains(Object o)判断o是否在集合中Iterator E iterator()迭代器boolean remove(Object o)删除集合中的oint size()返回set中的元素个数boolean isEmpty()判断是否为空Object[] toArray()将set中的元素转换为数组
例
public static void main(String[] args) {SetInteger set new TreeSet();set.add(1);set.add(2);set.add(3);set.add(4);set.add(5);System.out.println(set);System.out.println(set.size());System.out.println(set.contains(6));System.out.println(set.contains(5));Object[] arr set.toArray();System.out.println(-------------);for (Object o : arr) {System.out.print(o );}System.out.println();System.out.println(---------------);IteratorInteger iterator set.iterator();//迭代器,用于遍历setwhile (iterator.hasNext()) {System.out.print(iterator.next() );}
}输出结果 注意事项
1、set只存储了key值并且key是唯一的不能重复2、TreeSet的底层是使用Map来实现的插入key时value会默认插入一个Object对象3、TreeSet不能插入nullHashSet可以插入null