Java常见写法3
Java中常见的集合:
- List:
ArrayList和LinkedList - Map:
HashMap、EnumMap、TreeMap - Set:
HashSet,接口SortedSet,实现类TreeSet - Queue:
LinkedList、PriorityQueue - Deque:
LinkedList - Stack: 不要使用遗留类
Stack,用Deque可以实现Stack的功能,注意只调用push()/pop()/peek()方法,避免调用Deque的其他方法。
List
在集合类中,List是最基础的一种集合:它是一种有序列表。
我们考察List<E>接口,可以看到几个主要的接口方法:
- 在末尾添加一个元素:
boolean add(E e) - 在指定索引添加一个元素:
boolean add(int index, E e) - 删除指定索引的元素:
E remove(int index) - 删除某个元素:
boolean remove(Object e) - 获取指定索引的元素:
E get(int index) - 获取链表大小(包含元素的个数):
int size() contains()和indexOf()需要集合对象实现equals()方法
创建List
List<String> list = List.of("apple", "pear", "banana");
高效遍历List:比使用索引遍历效率高(特别对于LinkedList)
for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
String s = it.next();
System.out.println(s);
}
for(String s: list) {
System.out.println(s);
}
List与Array相互转换
// toArray()方法直接返回一个Object[]数组
Object[] array = list.toArray();
//
List<Integer> list = List.of(12, 34, 56);
Integer[] array = list.toArray(new Integer[list.size()]);
//
Integer[] array = list.toArray(Integer[]::new);
// Array to List
Integer[] array = { 1, 2, 3 };
List<Integer> list = List.of(array);
ArrayList
ArrayList在内部使用了数组来存储所有元素。例如,一个ArrayList拥有5个元素,实际数组大小为6(即有一个空位):
size=5
┌───┬───┬───┬───┬───┬───┐
│ A │ B │ C │ D │ E │ │
└───┴───┴───┴───┴───┴───┘
LinkedList
LinkedList在内部使用链表存储所有元素。
Map
┌───┐
│Map│
└───┘
▲
┌────┴─────┐
│ │
┌───────┐ ┌─────────┐
│HashMap│ │SortedMap│
└───────┘ └─────────┘
▲
│
┌─────────┐
│ TreeMap │
└─────────┘
HashMap
Set
┌───┐
│Set│
└───┘
▲
┌────┴─────┐
│ │
┌───────┐ ┌─────────┐
│HashSet│ │SortedSet│
└───────┘ └─────────┘
▲
│
┌─────────┐

浙公网安备 33010602011771号