温馨提示×

Java中put方法在集合类中的表现如何

小樊
81
2024-09-10 12:52:07
栏目: 编程语言

在Java中,put方法主要用于将键值对(key-value pairs)添加到Map集合类中。Map是一种键值对数据结构,它存储了唯一的键和与之关联的值。以下是put方法在不同Map实现类中的表现:

  1. HashMap:HashMap是基于哈希表实现的Map,它允许使用null作为键和值。put方法将指定的键值对添加到HashMap中。如果键已经存在于HashMap中,那么原来的值将被新值替换,并返回原来的值。如果键不存在,则将键值对添加到HashMap中,并返回null。
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);
  1. TreeMap:TreeMap是基于红黑树实现的有序Map。put方法将指定的键值对添加到TreeMap中。如果键已经存在于TreeMap中,那么原来的值将被新值替换,并返回原来的值。如果键不存在,则将键值对添加到TreeMap中,并返回null。
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("one", 1);
treeMap.put("two", 2);
treeMap.put("three", 3);
  1. LinkedHashMap:LinkedHashMap是基于双向链表和哈希表实现的有序Map。put方法将指定的键值对添加到LinkedHashMap中。如果键已经存在于LinkedHashMap中,那么原来的值将被新值替换,并返回原来的值。如果键不存在,则将键值对添加到LinkedHashMap中,并返回null。
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("one", 1);
linkedHashMap.put("two", 2);
linkedHashMap.put("three", 3);
  1. ConcurrentHashMap:ConcurrentHashMap是一个线程安全的HashMap实现。put方法将指定的键值对添加到ConcurrentHashMap中。如果键已经存在于ConcurrentHashMap中,那么原来的值将被新值替换,并返回原来的值。如果键不存在,则将键值对添加到ConcurrentHashMap中,并返回null。
ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("one", 1);
concurrentHashMap.put("two", 2);
concurrentHashMap.put("three", 3);

总之,put方法在Java的集合类中用于向Map中添加键值对。不同的Map实现类(如HashMap、TreeMap等)在内部实现和性能上可能有所不同,但它们都遵循相同的put方法的基本行为。

0