In Java, List, Set and Map are commonly used collection classes. They are all part of the Java collection framework and are used to store and manipulate a set of objects. Here's how to use them in detail:
-
List:
- List is an ordered collection that allows storing duplicate elements.
- Common List implementation classes include ArrayList and LinkedList.
- Create a List object:
List<String> list = new ArrayList<>(); // 使用ArrayList实现 List<Integer> list = new LinkedList<>(); // 使用LinkedList实现
- Commonly used methods:
- Add elements:
list.add(element)
,list.add(index, element)
,list.addAll(collection)
- Get elements:
list.get(index)
- Modify elements:
list.set(index, element)
- Delete elements:
list.remove(index)
,list.remove(element)
- Determine whether the element exists:
list.contains(element)
- Get the list size:
list.size()
- Traversing a list: You can use a for-each loop or an iterator to traverse.
- Add elements:
-
Set:
- Set is an unordered collection and does not allow duplicate elements to be stored.
- Common Set implementation classes include HashSet and TreeSet.
- Create a Set object:
Set<String> set = new HashSet<>(); // 使用HashSet实现 Set<Integer> set = new TreeSet<>(); // 使用TreeSet实现
- Commonly used methods:
- Add elements:
set.add(element)
- Delete elements:
set.remove(element)
- Determine whether the element exists:
set.contains(element)
- Get the collection size:
set.size()
- Traversing a collection: You can use a for-each loop or an iterator to traverse.
- Add elements:
-
Map:
- Map is a collection of key-value pairs, each key corresponds to a value, and the key is unique.
- Common Map implementation classes include HashMap and TreeMap.
- Create a Map object:
Map<String, Integer> map = new HashMap<>(); // 使用HashMap实现 Map<String, Integer> map = new TreeMap<>(); // 使用TreeMap实现
- Commonly used methods:
- Add key-value pairs:
map.put(key, value)
- Get value:
map.get(key)
- Modify value:
map.put(key, newValue)
- Delete key-value pairs:
map.remove(key)
- Determine whether the key exists:
map.containsKey(key)
- Determine whether the value exists:
map.containsValue(value)
- Get the number of key-value pairs:
map.size()
- Traverse key-value pairs: You can use a for-each loop or iterator to traverse, or use
map.entrySet()
a collection of key-value pairs to traverse.
- Add key-value pairs: