Java笔记:Java中的HashMap与HashSet

HashMap与HashSet

底层都是哈希表
1

2

  • Set: 纯key模型
  • Map:key-value模型
  • Set和Map的key值都不能重复,且都可以为null.
1 Map

方法解释

  • V get(Object key) : 返回key 对应的value
  • V getOrDefault(Object key, V defaultValue) : 返回key
    对应的value,key不存在,返回默认值
  • V put(K key, V value): 设置key 对应的value
  • V remove(Object key): 删除key 对应的映射关系
  • Set<K> keySet(): 返回所有key 的不重复集合
  • Collection<V> values(): 返回所有value 的可重复集合
  • Set<Map.Entry<K, V>> entrySet(): 返回所有的key-value 映射关系
  • boolean containsKey(Object key): 判断是否包含key
  • boolean containsValue(Object value): 判断是否包含value

对于entrySet()方法:

Set<Map.Entry<K, V>>  entrySet():  

entrySet()方法返回一个Set集合,集合里面元素的类型为Map.Entry<K,V>。

Map方法Code:

import java.util.Map;
public static void main1(String[] args) {
Map<Integer,String> map = new HashMap<>();
map.put(1,"abc");
map.put(10,"hello");
map.put(null,"goh");

//获取key的集合
Set<Integer> set = map.keySet();
System.out.println(set);

//获取value的集合
Collection<String>collection =  map.values();
System.out.println(collection);
//map.entrySet()获取key-value集合
for ( Map.Entry<Integer, String> entrySet : map.entrySet()) {
   System.out.println(entrySet.getKey()+" "
   +entrySet.getValue());
}
}
2 Set

方法解释
boolean add(E e): 添加元素,但重复元素不会被添加成功
void clear(): 清空集合
boolean contains(Object o): 判断o 是否在集合中
Iterator<E> iterator(): 返回迭代器
boolean remove(Object o): 删除集合中的o

Map没有实现iterable接口,不能使用迭代器,而像List, Queue, Set都实现了iterable接口.

Set方法Code:

import java.util.Set;
public static void main(String[] args) {
    Set<Integer> set = new HashSet<>();
    set.add(1);
    set.add(2);
    System.out.println(set);
    //只要实现了iterable接口,就可以使用迭代器
    Iterator<Integer> iterator = set.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
发布了54 篇原创文章 · 获赞 6 · 访问量 4801

猜你喜欢

转载自blog.csdn.net/glpghz/article/details/104433759