溫馨提示×

Java中put方法在集合類中的表現如何

小樊
109
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女