> Java的java.util
軟件包提供了Collection
>接口,該接口分為幾個子接口和類,包括List
>,Set
和Map
接口List
的一個子接口提供了用於插入,更新,刪除和搜索元素的方法。 重要的是,List
允許重複元素並保持插入順序。還允許NULL元素。 Collection
List
接口示例: List
<code class="language-java">import java.util.*; public class ListExample { public static void main (String args[]) { List<string> mylist = new ArrayList<>(); mylist.add("James Bond"); mylist.add("Superman"); mylist.add("Spiderman"); for(String superhero : mylist) System.out.println(superhero); } }</string></code>輸出:
<code>James Bond Superman Spiderman</code>>了解
接口Set
sub-interface位於Set
的定義特徵是它拒絕重複元素。僅存儲唯一的值。 插入順序是Collection
不保證的。 java.util
>
Set
接口示例:
Set
輸出:
<code class="language-java">import java.util.*; public class MySet { public static void main (String args[]) { Set<string> setmyalp = new HashSet<>(); setmyalp.add("A"); setmyalp.add("B"); setmyalp.add("C"); setmyalp.add("D"); setmyalp.add("E"); System.out.println(setmyalp); } }</string></code>
>了解
接口<code>[A, B, C, D, E] (Order may vary)</code>
Map
接口,也可以在中找到,將數據存儲在鍵值對中。 每個鍵都是唯一的,用於檢索其關聯的值。 不允許重複鍵。 不能保證插入順序。
Map
java.util
接口示例:
Map
輸出:
<code class="language-java">import java.util.*; public class MyMap { public static void main (String args[]) { Map<string string> mapvalue = new HashMap<>(); mapvalue.put("Fruit", "Apple"); mapvalue.put("Vegetable", "Potato"); mapvalue.put("Nut", "Groundnut"); for(Map.Entry<string string> me : mapvalue.entrySet()) { System.out.println(me.getKey() + " " + me.getValue()); } } }</string></string></code>
>
,<code>Fruit Apple Vegetable Potato Nut Groundnut (Order may vary)</code>和
接口之間的密鑰差異
Feature | List |
Set |
Map |
---|---|---|---|
Duplicates | Allowed | Not Allowed | Not Allowed (for keys) |
Insertion Order | Maintained | Not Guaranteed | Not Guaranteed |
Null Values | Multiple allowed | Only one allowed | One null key allowed, multiple null values |
Implementing Classes |
ArrayList , LinkedList , etc. |
HashSet , LinkedHashSet , TreeSet , etc. |
HashMap , LinkedHashMap , TreeMap , etc. |
Element Access | By index using get() method |
No direct index access | By key using get() method |
Use Case | Ordered collections, sequences | Unique elements, membership testing | Key-value associations, lookups |
Iteration | ListIterator |
Iterator |
keySet() , values() , entrySet()
|
結論
List
,Set
和Map
是基本的Java界面,提供了管理數據集合的不同方法。 選擇完全取決於您應用程序的特定需求,考慮了諸如對有序元素的需求,重複津貼以及所需數據訪問的性質等因素。
常見問題(FAQS)>
package:>,List
,Set
Map
屬於java.util
> package。
>允許多個nulls; List
>僅允許一個; Set
允許一個空鍵和多個空值。 Map
實現:List
是常見的實現。 >
ArrayList
LinkedList
允許重複值。
List
方法:僅get()
和(對於通過鍵的值)提供索引或鍵的直接元素訪問。 List
> Map
以上是Java中的列表,設置和地圖之間的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!