Table of contents
Overview
Java provides a rich set of data structures to handle various programming tasks, including basic data types, collection frameworks, and custom data structures. Here are some common Java data structures:
-
Basic data types: Java's basic data types include integers (int, byte, short, long), floating point numbers (float, double), characters (char), Boolean (boolean), etc.
-
Array: An array is a collection of elements of the same type that has a fixed size. In Java, the size of an array is determined when it is created and cannot be changed.
-
Collection Framework: Java provides a set of collection frameworks for storing and manipulating objects. These collection frameworks include:
- List interface: an ordered collection that can contain repeated elements. Common implementation classes include ArrayList and LinkedList.
- Set interface: a collection that does not allow duplicate elements. Common implementation classes include HashSet, LinkedHashSet and TreeSet.
- Map interface: a collection of key-value pairs, each key maps to a unique value. Common implementation classes include HashMap, LinkedHashMap and TreeMap.
- Queue interface: Queue, supports inserting elements at one end of the queue and removing elements at the other end. Common implementation classes include LinkedList and PriorityQueue.
-
Stack: Stack is a special data structure that follows the last-in-first-out (LIFO) principle. A stack can be implemented using Java's Stack class.
-
LinkedList: A linked list is a linear data structure containing nodes, with each node pointing to the next node. Java's LinkedList class implements a doubly linked list.
-
Tree: A tree is a hierarchical data structure, including root nodes, child nodes, and leaf nodes. Java provides TreeSet and TreeMap to implement tree structures.
-
Graph: A graph is a complex data structure composed of nodes and edges used to represent relationships between entities. In Java, you can use custom data structures to represent graphs, or you can use graph algorithm libraries.
-
Heap: Heap is a special tree structure usually used to implement priority queues. Java's PriorityQueue class uses a heap to maintain the order of elements.
-
HashTable: A hash table is a data structure that uses a hash function to map keys to values. Java's HashMap and Hashtable classes are both implementations of hash tables.
-
Custom data structure: Based on specific needs, you can also create custom data structures, such as stacks, queues, linked lists, trees, etc.
These data structures provide a wide range of applications in Java, and appropriate data structures can be selected to implement algorithms and data processing tasks according to the nature of the problem. Java's collection framework is particularly powerful and provides the implementation of various data structures to meet the needs of different scenarios.
introduce
1、Array
In Java, an array is a data structure used to store elements of the same data type. Arrays have a fixed size and once created, their size cannot be changed. Each array element can be accessed by index, starting from 0 and increasing in sequence.
Example
- Declare and create arrays:
dataType[] arrayName; // 声明数组
arrayName = new dataType[arraySize]; // 创建数组
// 或者
int[] numbers; // 声明整数数组
numbers = new int[5]; // 创建包含5个整数元素的数组
// 或者
int[] numbers = new int[5]; // 声明并创建整数数组
- Initialize the array:
int[] numbers = {1, 2, 3, 4, 5}; // 初始化整数数组
String[] names = {"Alice", "Bob", "Charlie"}; // 初始化字符串数组
-
Accessing array elements: Use indexing to access array elements. The index starts from 0 and increases sequentially.
int firstNumber = numbers[0]; // 获取第一个元素(索引为0)
String secondName = names[1]; // 获取第二个元素(索引为1)
-
Array length: Use
length
the property to get the length of an array.
int length = numbers.length; // 获取整数数组的长度(包含5个元素)
- Multidimensional Arrays: Java supports multidimensional arrays such as two-dimensional arrays (arrays of arrays).
int[][] matrix = {
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 二维整数数组
int element = matrix[1][2]; // 访问二维数组中的元素
- Array traversal: You can use loops to iterate over the elements in an array.
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Or use an enhanced for
loop (for-each loop):
for (int number : numbers) {
System.out.println(number);
}
Array is a common data structure in Java, used to store and manipulate a set of data. Please choose to use arrays according to specific needs and scenarios. If you need a more flexible data structure, you can consider using collection classes (such as ArrayList, LinkedList, etc.) instead of arrays.
2、ArrayList
ArrayList
It is a commonly used collection class in Java. It is part of the Java collection framework and is located in java.util
the package. ArrayList
Provides an implementation of dynamic arrays, allowing the storage and management of a set of objects. Unlike ordinary arrays, ArrayList
the size of an array can be dynamically adjusted and can automatically expand to accommodate more elements.
Example
- Declare and create ArrayList:
import java.util.ArrayList;
// 声明一个整数类型的 ArrayList
ArrayList<Integer> numbers = new ArrayList<Integer>();
// 声明一个字符串类型的 ArrayList
ArrayList<String> names = new ArrayList<String>();
-
Add elements:
add
Elements can be added to using the method ArrayList
:
numbers.add(10);
numbers.add(20);
names.add("Alice");
names.add("Bob");
-
Get elements:
Use the method to get elements in get
based on index :ArrayList
int firstNumber = numbers.get(0); // 获取第一个元素
String secondName = names.get(1); // 获取第二个元素
-
Modify elements:
Use set
the method to modify ArrayList
an element in based on its index:
numbers.set(0, 30); // 将第一个元素修改为30
names.set(1, "Charlie"); // 将第二个元素修改为"Charlie"
-
Delete elements:
Use the method to delete elements in remove
based on index or object :ArrayList
numbers.remove(0); // 删除第一个元素
names.remove("Alice"); // 删除指定元素
-
Get the size:
Use size
the method to get ArrayList
the size (number of elements) of :
int size = numbers.size(); // 获取整数 ArrayList 的大小
-
Iterate over elements:
You can use a loop to iterate over ArrayList
the elements in :
for (int i = 0; i < numbers.size(); i++) {
int number = numbers.get(i);
System.out.println(number);
}
for (String name : names) {
System.out.println(name);
}
-
Short judgment:
You can use isEmpty
the method to check ArrayList
if is empty:
boolean isEmpty = numbers.isEmpty(); // 检查整数 ArrayList 是否为空
ArrayList
It is a flexible and commonly used data structure, suitable for situations where a collection of elements needs to be dynamically managed. It should be noted that since ArrayList
it is implemented based on an array, inserting and deleting elements is expensive. If you need to perform frequent insertion and deletion operations, you may need to consider other collection classes, such as LinkedList
.
3、LinkedList
LinkedList
It is a doubly linked list data structure in Java. It implements List
the and Deque
interfaces and is part of the Java collection framework, located in java.util
the package. Unlike ArrayList
, LinkedList
it is not implemented based on an array, but organizes elements through links between nodes.
Linked list structure:
LinkedList
Use a linked list structure to store elements. Each element (node) contains a data item and two pointers, pointing to the previous node and the next node respectively, which makes inserting and deleting elements in the linked list relatively easy.Doubly linked list:
LinkedList
It is a doubly linked list, which means that you can start from any node and traverse the linked list forward or backward, which helps in performing forward and backward operations in the linked list.Random access is slower: Unlike
ArrayList
,LinkedList
fast random access is not supported. To access elements in a linked list, you usually need to start from the head node (or tail node) and traverse the linked list one by one, so the time complexity of random access is O(n).Insertion and deletion operations: Due to the structure of the linked list, operations of inserting and deleting elements
LinkedList
are relatively efficient in . The time complexity of inserting or deleting a node in a linked list is O(1).
Example
import java.util.LinkedList;
// 创建一个 LinkedList
LinkedList<String> linkedList = new LinkedList<>();
// 向链表添加元素
linkedList.add("Alice");
linkedList.add("Bob");
linkedList.add("Charlie");
// 在指定位置插入元素
linkedList.add(1, "David");
// 访问元素
String first = linkedList.getFirst();
String last = linkedList.getLast();
// 删除元素
linkedList.remove(2); // 删除索引为2的元素
// 遍历链表
for (String name : linkedList) {
System.out.println(name);
}
// 获取链表的大小
int size = linkedList.size();
In short, LinkedList
it is a flexible data structure, especially suitable for scenarios that require frequent insertion and deletion operations. However, if a large number of random access elements are required, ArrayList
it may be more suitable because of LinkedList
poor random access performance. Depending on the specific application scenario, it is important to choose the appropriate data structure.
4、HashSet
HashSet
It is a collection class in Java, which implements Set
the interface, is part of the collection framework, and is located java.util
in the package. HashSet
It is mainly used to store a set of non-repeating elements. It does not guarantee the order of elements and does not allow repeated elements.
Non-repeating elements:
HashSet
The stored elements are non-repeating. If you try toHashSet
add an existing element to , the addition operation will be ignored and will not cause repeated elements.Unordered collection:
HashSet
The order of elements is not guaranteed. The order in which elementsHashSet
are stored in may differ from the order in which they are added.Hash table based:
HashSet
A hash table is used internally to store elements. This makes the operations of adding, removing and finding elements typically have constant time complexity, i.e. O(1).Supports null elements:
HashSet
allows storage of onenull
element, but only one, since duplicate elements are not allowed in the collection.
Example
import java.util.HashSet;
import java.util.Set;
// 创建一个 HashSet
Set<String> hashSet = new HashSet<>();
// 向 HashSet 添加元素
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
// 判断元素是否存在
boolean containsBanana = hashSet.contains("Banana"); // 返回 true
// 删除元素
hashSet.remove("Cherry");
// 遍历 HashSet
for (String fruit : hashSet) {
System.out.println(fruit);
}
// 获取 HashSet 的大小
int size = hashSet.size();
In short, HashSet
it is a commonly used collection class, suitable for situations where a set of unique elements needs to be stored. It is often the preferred collection type due to its efficient add, delete, and find operations. If you need to maintain the order of elements or allow duplicate elements, consider using other collection types such as LinkedHashSet
or TreeSet
.
5、LinkedHashSet
LinkedHashSet
It is a collection class in Java. It is HashSet
a variant of and implements Set
the interface and is located java.util
in the package. Unlike normal HashSet
, LinkedHashSet
a linked list is used internally to maintain the order of elements, so it preserves the insertion order of elements.
-
Ordered set:
LinkedHashSet
The insertion order of elements is preserved, so it is an ordered set. When you iterate overLinkedHashSet
, the elements are in the same order as they were added to the collection. -
Non-repeating elements:
LinkedHashSet
The stored elements are non-repeating, and repeated elements are not allowed. -
Based on hash tables and linked lists:
LinkedHashSet
Internally, a hash table is used to quickly find elements, and a linked list is used to maintain the order of elements. This makes the operations of adding, removing and finding elements typically have constant time complexity, i.e. O(1). -
Supports null elements:
LinkedHashSet
allows storage of onenull
element, but only one, since duplicate elements are not allowed in the collection.
Example
import java.util.LinkedHashSet;
import java.util.Set;
// 创建一个 LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<>();
// 向 LinkedHashSet 添加元素
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Cherry");
// 保留元素的插入顺序
// 遍历 LinkedHashSet 时,元素的顺序与添加顺序相同
for (String fruit : linkedHashSet) {
System.out.println(fruit);
}
// 判断元素是否存在
boolean containsBanana = linkedHashSet.contains("Banana"); // 返回 true
// 删除元素
linkedHashSet.remove("Cherry");
// 获取 LinkedHashSet 的大小
int size = linkedHashSet.size();
In short, LinkedHashSet
it is an ordered set that preserves the insertion order of elements. LinkedHashSet
A good choice if you need to maintain the order of elements in a collection and do not allow duplicate elements . Its performance characteristics HashSet
are similar to ordinary , but its ordered nature makes it suitable for specific application scenarios.
6、TreeSet
TreeSet
It is a collection class in Java. It implements NavigableSet
the interface and is SortedSet
an implementation of the interface. It is located java.util
in the package. TreeSet
It is an ordered set that uses the Red-Black Tree data structure to maintain the order of elements and has the following characteristics:
- Sorted Set:
TreeSet
is an ordered set that sorts elements according to their natural ordering or a specified comparator. By default,TreeSet
the natural ordering of elements is used for sorting.- Non-repeating elements:
TreeSet
The stored elements are non-repeating, and repeated elements are not allowed.- Based on red-black tree:
TreeSet
Internally uses red-black tree data structure to store elements. This data structure ensures fast search, insertion and deletion of elements, with a time complexity of O(log n).- Natural or custom sorting: Elements can be sorted according to their natural order (if the element implements
Comparable
the interface) or by providing a custom comparator ( ).Comparator
- Traversal order: When you iterate over
TreeSet
, the elements will be iterated in sorted order.- Null elements are not supported:
TreeSet
storage ofnull
elements is not allowed.
Example
import java.util.TreeSet;
import java.util.Set;
// 创建一个 TreeSet
Set<String> treeSet = new TreeSet<>();
// 向 TreeSet 添加元素
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Cherry");
// 遍历 TreeSet,按照排序顺序输出
for (String fruit : treeSet) {
System.out.println(fruit);
}
// 判断元素是否存在
boolean containsBanana = treeSet.contains("Banana"); // 返回 true
// 删除元素
treeSet.remove("Cherry");
// 获取 TreeSet 的大小
int size = treeSet.size();
In short, TreeSet
it is an ordered collection, suitable for situations where elements need to be sorted. It has efficient insertion, deletion and lookup operations, but balances the red-black tree during insertion and deletion operations, so the performance of insertion and deletion operations is slightly lower HashSet
. Depending on your sorting requirements and performance needs, it's important to choose the appropriate collection type.
7、HashMap
HashMap
It is a collection class in Java that implements Map
the interface and is used to store key-value pairs. HashMap
Using a key as an index allows you to quickly find and retrieve the value associated with the key. Here are HashMap
some important features and uses of :
Key-value pair storage:
HashMap
The stored data is a collection of key-value pairs. Each key is unique and each key is associated with a value.Unique keys:
HashMap
The keys in are unique. If you try to add an existing key, the new value will overwrite the original value.Hash table-based:
HashMap
Implemented internally using a hash table data structure, which makes search, insertion, and deletion operations usually have constant time complexity, that is, O(1). But in some cases, hash collisions can cause performance degradation.Unordered collection:
HashMap
The order of the elements is not guaranteed, that is, the order in which the elements are stored may be different from the order in which they were added. Consider using this if you need ordered key-value pairsLinkedHashMap
.Allow null keys and values:
HashMap
Allows storing onenull
key and multiplenull
values.Thread-unsafe:
HashMap
It is not thread-safe. If multiple threads access and modify the sameHashMap
instance at the same time, it may cause data inconsistency and concurrency problems. You can useCollections.synchronizedMap()
the method orConcurrentHashMap
to obtain a thread-safe version.
Example
import java.util.HashMap;
import java.util.Map;
// 创建一个 HashMap
Map<String, Integer> hashMap = new HashMap<>();
// 向 HashMap 添加键值对
hashMap.put("Alice", 25);
hashMap.put("Bob", 30);
hashMap.put("Charlie", 28);
// 获取键对应的值
int age = hashMap.get("Bob"); // 返回 30
// 判断是否包含键
boolean containsAlice = hashMap.containsKey("Alice"); // 返回 true
// 删除键值对
hashMap.remove("Charlie");
// 遍历 HashMap
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
String name = entry.getKey();
int value = entry.getValue();
System.out.println(name + ": " + value);
}
// 获取 HashMap 的大小
int size = hashMap.size();
8、LinkedHashMap
LinkedHashMap
It is a collection class in Java. It is HashMap
a variant of and implements Map
the interface and is located java.util
in the package. Different from ordinary HashMap
, LinkedHashMap
a hash table and a doubly linked list are used internally to maintain the order of elements, so it has the following characteristics:
-
Ordered set:
LinkedHashMap
The insertion order of elements is preserved, so it is an ordered set. When you iterate overLinkedHashMap
, the elements are in the same order as they were added to the collection. -
Non-duplicate keys:
LinkedHashMap
The keys in are non-duplicate and duplicate keys are not allowed. -
Based on hash table and doubly linked list:
LinkedHashMap
Internally, a hash table is used to quickly find elements, and a doubly linked list is used to maintain the insertion order of elements. This data structure enablesLinkedHashMap
fast searching and traversing of elements. -
Sorting can be specified:
LinkedHashMap
allows you to sort elements according to insertion order or access order. You canLinkedHashMap
choose the sorting method by passing in parameters when constructing. -
Null keys and values are not supported:
LinkedHashMap
storingnull
keys and values is not allowed.
Example
import java.util.LinkedHashMap;
import java.util.Map;
// 创建一个 LinkedHashMap
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
// 向 LinkedHashMap 添加键值对
linkedHashMap.put("Alice", 25);
linkedHashMap.put("Bob", 30);
linkedHashMap.put("Charlie", 28);
// 保留元素的插入顺序
// 遍历 LinkedHashMap 时,元素的顺序与添加顺序相同
for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
String name = entry.getKey();
int value = entry.getValue();
System.out.println(name + ": " + value);
}
// 判断是否包含键
boolean containsBob = linkedHashMap.containsKey("Bob"); // 返回 true
// 删除键值对
linkedHashMap.remove("Charlie");
// 获取 LinkedHashMap 的大小
int size = linkedHashMap.size();
In short, LinkedHashMap
it is an ordered collection, suitable for situations where the insertion order of elements needs to be maintained. It has the ability to quickly find and traverse elements and is a common choice for ordered collections. You can use this if you need to sort elements according to their sorting rules TreeMap
.
9、TreeMap
TreeMap
It is a collection class in Java. It implements NavigableMap
the interface and is SortedMap
an implementation of the interface. It is located java.util
in the package. TreeMap
It is an ordered mapping based on the red-black tree data structure and has the following characteristics:
-
Ordered Map:
TreeMap
is an ordered map that sorts the keys according to their natural order or a specified comparator. By default,TreeMap
the natural ordering of keys is used for sorting. -
Non-duplicate keys:
TreeMap
The keys in are non-duplicate and duplicate keys are not allowed. If you try to add an existing key, the new value will overwrite the original value. -
Based on red-black tree:
TreeMap
Internally uses the red-black tree (Red-Black Tree) data structure to store key-value pairs. This data structure ensures fast search, insertion and deletion of keys with a time complexity of O(log n). -
Natural or custom sorting: Keys can be sorted according to their natural ordering (if the key implements
Comparable
the interface) or by providing a custom comparator ( ).Comparator
-
Traversal order: When you iterate over
TreeMap
, the key-value pairs will be iterated in sorted order. -
Null keys are not supported:
TreeMap
storingnull
keys is not allowed, butnull
values can be stored.
Example
import java.util.TreeMap;
import java.util.Map;
// 创建一个 TreeMap
Map<String, Integer> treeMap = new TreeMap<>();
// 向 TreeMap 添加键值对
treeMap.put("Alice", 25);
treeMap.put("Bob", 30);
treeMap.put("Charlie", 28);
// 遍历 TreeMap,按照排序顺序输出
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
String name = entry.getKey();
int value = entry.getValue();
System.out.println(name + ": " + value);
}
// 获取键对应的值
int age = treeMap.get("Bob"); // 返回 30
// 判断是否包含键
boolean containsAlice = treeMap.containsKey("Alice"); // 返回 true
// 删除键值对
treeMap.remove("Charlie");
// 获取 TreeMap 的大小
int size = treeMap.size();
In short, TreeMap
it is an ordered mapping, suitable for situations where data needs to be stored and accessed according to the sorting rules of the keys. It has efficient insertion, deletion and lookup operations, but balances the red-black tree during insertion and deletion operations, so the performance of insertion and deletion operations is slightly lower HashMap
. Depending on your sorting requirements and performance needs, it's important to choose the appropriate collection type.
10、HashTable
Hashtable
It is a collection class in Java, which implements Map
the interface and is located java.util
in the package. Hashtable
It is a collection based on hash table data structure and has the following characteristics:
-
Key-value pair storage:
Hashtable
The stored data is a collection of key-value pairs. Each key is unique and each key is associated with a value. -
Unique keys:
Hashtable
The keys in are unique. If you try to add an existing key, the new value will overwrite the original value. -
Hash table-based:
Hashtable
Implemented internally using a hash table data structure, which makes search, insertion, and deletion operations usually have constant time complexity, that is, O(1). -
Thread safety:
Hashtable
It is thread safe. Multiple threads can access and modify the sameHashtable
instance at the same time without causing data inconsistency. But this also means that in a multi-threaded environment,Hashtable
the performance will be relatively low. Consider using this if thread safety is not requiredHashMap
. -
Null keys and values are not supported:
Hashtable
storingnull
keys and values is not allowed. -
Unordered traversal:
Hashtable
The order of elements is not guaranteed, that is, the storage order of elements may be different from the order in which they were added.
Example
import java.util.Hashtable;
import java.util.Map;
// 创建一个 Hashtable
Map<String, Integer> hashtable = new Hashtable<>();
// 向 Hashtable 添加键值对
hashtable.put("Alice", 25);
hashtable.put("Bob", 30);
hashtable.put("Charlie", 28);
// 获取键对应的值
int age = hashtable.get("Bob"); // 返回 30
// 判断是否包含键
boolean containsAlice = hashtable.containsKey("Alice"); // 返回 true
// 删除键值对
hashtable.remove("Charlie");
// 遍历 Hashtable
for (Map.Entry<String, Integer> entry : hashtable.entrySet()) {
String name = entry.getKey();
int value = entry.getValue();
System.out.println(name + ": " + value);
}
// 获取 Hashtable 的大小
int size = hashtable.size();
In short, Hashtable
it is a thread-safe hash table collection, suitable for situations that need to be used in a multi-threaded environment. It has fast find, insert, and delete operations, but has relatively low performance in a multi-threaded environment. Consider using this if thread safety is not required HashMap
.
11、ConcurrentHashMap
ConcurrentHashMap
It is a thread-safe hash table implementation in the Java collection framework. It was introduced in Java 5 to solve the problem of concurrent access to HashMap in a multi-threaded environment. ConcurrentHashMap
Supports highly concurrent read and write operations without explicit locking, so it performs well in multi-threaded environments.
Thread safety:
ConcurrentHashMap
It is thread-safe, multiple threads can read and write data at the same time without causing data inconsistency or concurrency issues.Segment lock:
ConcurrentHashMap
The concept of segment lock is used to internally divide the data into multiple segments (Segments), and each segment is locked independently. This means that operations in different segments can be executed concurrently, improving concurrency performance.High concurrent reading: In
ConcurrentHashMap
, multiple threads can read data at the same time without blocking. This makes the performance very high in scenarios where there is a lot of reading and a lot of writing.Suitable for high concurrent writes: While read operations can be highly concurrent, write operations can also be performed concurrently on different segments, so it
ConcurrentHashMap
still performs well in the case of high concurrent writes.Lock-free read: In read operations,
ConcurrentHashMap
locking is usually not required, so it is lock-free for read operations.Allow null key values: Unlike HashMap,
ConcurrentHashMap
both keys and values are allowed to be null.Performance optimization: Java 8 and later versions have
ConcurrentHashMap
performance optimizations to further improve concurrency performance.
Example usage
ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
// 添加元素
concurrentMap.put("key1", 1);
concurrentMap.put("key2", 2);
// 获取元素
int value = concurrentMap.get("key1");
// 删除元素
concurrentMap.remove("key2");
// 遍历元素
concurrentMap.forEach((key, val) -> {
System.out.println(key + ": " + val);
});
In short, ConcurrentHashMap
it is a powerful tool for handling concurrent access to hash tables in a multi-threaded environment. It is suitable for high concurrent reading and writing scenarios and can provide good performance and thread safety.
12、Stack
Stack
It is a collection class in Java that implements the stack data structure. A stack is a Last-In-First-Out (LIFO) data structure that is typically used to add or remove elements from the top. Stack
Classes inherit from Vector
class and are located java.util
in the package.
-
Last-in-first-out: The stack is a last-in-first-out data structure, and the last element added will be the first to be removed.
-
Array-based:
Stack
Arrays are used internally to store elements, so they have the ability to dynamically expand. -
Main operations:
push(E item)
:Push the element onto the top of the stack.pop()
: Remove and return the top element of the stack.peek()
: Returns the top element of the stack, but does not remove it.empty()
: Check whether the stack is empty.search(Object o)
: Find the position of the element in the stack and return the distance from the top of the stack.
Example
import java.util.Stack;
// 创建一个 Stack
Stack<Integer> stack = new Stack<>();
// 压入元素
stack.push(1);
stack.push(2);
stack.push(3);
// 弹出元素
int popped = stack.pop(); // 弹出并返回 3
// 查看栈顶元素
int top = stack.peek(); // 返回 2,但不移除
// 检查栈是否为空
boolean isEmpty = stack.isEmpty(); // 返回 false
// 查找元素在栈中的位置
int index = stack.search(1); // 返回 2,表示距离栈顶的第 2 个元素是 1
In short, Stack
it is a last-in-first-out data structure that is often used to temporarily store and manage data, such as in algorithms, recursion, and expression evaluation. In actual development, since Stack
is Vector
a subclass of , it is usually recommended to use Deque
the implementation class of the (double-ended queue) interface LinkedList
as an alternative to the stack, because LinkedList
it supports both stack operations and queue operations, and has better performance.
13、PriorityQueue
PriorityQueue
It is a collection class in Java. It implements the Queue interface and is a special queue used to store elements with priority. Elements are stored in the queue and dequeued based on their priority. PriorityQueue
Is an implementation of a Min-Heap, where the top element is the element with the highest priority. Located java.util
in the package.
-
Priority queue:
PriorityQueue
is a priority queue in which the elements are ordered according to their priority. By default, elements are considered to be sorted in natural order, or you can provide a custom comparator to specify the ordering. -
Insertion and deletion operations:
PriorityQueue
Supports insertion (offer()
oradd()
method) and deletion (poll()
method) operations. Insertion operations add elements to the queue, and deletion operations remove and return the highest priority element in the queue. -
Null elements not allowed:
PriorityQueue
Null elements are not allowed to be stored. -
Based on heap:
PriorityQueue
Internally implemented using the binary heap data structure, which is a complete binary tree that ensures that the efficiency of insertion and deletion is O(log n), where n is the size of the queue. -
Custom sorting:
Comparator
You can specify how elements are sorted by providing a custom comparator ( ). This allows you to define any type of precedence relationship between elements.
Example
import java.util.PriorityQueue;
import java.util.Queue;
// 创建一个 PriorityQueue,默认按自然顺序排序
Queue<Integer> priorityQueue = new PriorityQueue<>();
// 插入元素
priorityQueue.offer(5);
priorityQueue.offer(3);
priorityQueue.offer(8);
// 删除并返回最高优先级元素
int highestPriority = priorityQueue.poll(); // 返回 3
// 创建一个自定义排序的 PriorityQueue
Queue<String> customPriorityQueue = new PriorityQueue<>((a, b) -> b.length() - a.length());
// 插入元素,根据长度倒序排序
customPriorityQueue.offer("apple");
customPriorityQueue.offer("banana");
customPriorityQueue.offer("cherry");
// 删除并返回最高优先级元素
String highestLength = customPriorityQueue.poll(); // 返回 "banana"
In short, PriorityQueue
it is an ordered collection used to implement a priority queue. It is very useful in many applications, such as task scheduling, load balancing, etc., and can be sorted and processed according to the priority of elements. Flexible sorting can be achieved by providing custom comparators.
14、Tree
In Java, "Tree" is usually used to describe a tree data structure or a tree collection, rather than specifically referring to a class named "Tree". Tree is an important data structure that organizes and stores data in a hierarchical structure and is often used to implement search, sorting, hierarchical structures, etc.
-
TreeNode
Interface: Typically, the nodes of the tree implementTreeNode
an interface or its sub-interfacesMutableTreeNode
. These interfaces provide basic operations for nodes in the tree, such as getting parent nodes, getting child nodes, adding child nodes, etc. -
TreeModel
Interface:TreeModel
An interface is used to represent a tree data model, oftenJTree
used in conjunction with a graphical user interface (GUI) tree control such as GUI. It defines how data is organized and accessed in a tree structure. -
DefaultMutableTreeNode
Class: This is a commonly used tree node implementation class, usually used to create mutable trees (Mutable Tree). -
JTree
Class:JTree
is a graphical user interface component in Java Swing used to display and interact with tree data structures. It is typicallyTreeModel
used with the and node classes. -
Tree traversal algorithm: Java can use recursive or iterative methods to implement tree traversal, including pre-order traversal, in-order traversal, post-order traversal, and level-order traversal. These traversal algorithms are used to access the nodes of a tree.
-
Binary tree class: In Java, you can customize the nodes and binary tree data structures of binary trees, which are used to implement binary tree operations, such as binary search trees (BST), etc.
Example
Create a simple mutable tree using DefaultMutableTreeNode
andJTree
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class SimpleTreeExample {
public static void main(String[] args) {
// 创建根节点
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
// 创建子节点
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");
// 添加子节点到根节点
root.add(node1);
root.add(node2);
// 创建树模型
DefaultTreeModel treeModel = new DefaultTreeModel(root);
// 创建树控件
JTree tree = new JTree(treeModel);
// 创建窗口并添加树控件
JFrame frame = new JFrame("Simple Tree Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.pack();
frame.setVisible(true);
}
}
This example creates a simple mutable tree with a root node and two child nodes, and then JTree
displays it via .
In summary, trees in Java can be implemented in a variety of ways and classes for representing and processing data with hierarchical structures. In graphical user interface development, JTree
it is a commonly used tree control for displaying and operating tree data. Among algorithms and data structures, tree structures are also widely used to solve problems such as search, sorting, and hierarchical structures.
15、Graph
In Java, the data structure representing graph (Graph) usually needs to be implemented by yourself, because the Java standard library does not provide a specialized Graph
class. Graph is a very important data structure used to represent relationships between multiple objects. It includes nodes (vertices) and edges (connections). Here is a common way to represent and manipulate graphs:
-
Node class (Vertex): Typically, you need to create a node class to represent each node in the graph. A node class typically includes a unique identifier that identifies the node, as well as other information related to the node.
-
Edge: Edge is used to connect two nodes and usually includes some additional information, such as weight.
-
Graph: The graph class is used to represent the entire graph, which includes a node set and an edge set. You can choose to implement the graph using an adjacency matrix, adjacency linked list, or other data structure.
Example
The following is a simple example showing how to represent a directed graph (Directed Graph) in Java:
import java.util.ArrayList;
import java.util.List;
class Vertex {
private int id;
private List<Edge> edges;
public Vertex(int id) {
this.id = id;
this.edges = new ArrayList<>();
}
public int getId() {
return id;
}
public List<Edge> getEdges() {
return edges;
}
public void addEdge(Vertex destination, int weight) {
edges.add(new Edge(this, destination, weight));
}
}
class Edge {
private Vertex source;
private Vertex destination;
private int weight;
public Edge(Vertex source, Vertex destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
public Vertex getSource() {
return source;
}
public Vertex getDestination() {
return destination;
}
public int getWeight() {
return weight;
}
}
public class DirectedGraph {
private List<Vertex> vertices;
public DirectedGraph() {
this.vertices = new ArrayList<>();
}
public void addVertex(Vertex vertex) {
vertices.add(vertex);
}
public List<Vertex> getVertices() {
return vertices;
}
}
In this example, we define Vertex
the class to represent the nodes in the graph, Edge
the class to represent the edges, and DirectedGraph
the class to represent the directed graph. You can create nodes, add edges, and build a directed graph.
It should be noted that the above example is a simple demonstration, and actual applications may require more complex data structures and algorithms to represent and operate graphs. In addition, there are some Java third-party libraries, such as JGraphT and JUNG, which provide more advanced graph processing functions and can be selected and used according to specific needs.
16、Heap
In Java, "Heap" usually refers to heap memory, not the heap in the data structure. Heap memory is a part of the memory used to store objects in the Java Virtual Machine (JVM), as opposed to stack memory. Here is some important information about Java heap memory:
-
Java Heap Memory: Heap memory is the memory area used to store object instances in a Java program. It is the core part of Java memory management and is used to dynamically allocate and deallocate object memory. The size of the heap memory can be configured through the JVM startup parameters.
-
Object allocation: When you create a new object, it usually allocates memory space in the heap memory. The life cycle of objects in heap memory is not limited by methods, but is managed by the object's reference and garbage collection mechanism.
-
Garbage collection: Objects in heap memory will not exist forever. The Java garbage collection mechanism will regularly scan the heap memory, mark and recycle objects that are no longer referenced, and release the memory they occupy. This helps prevent memory leaks and manage memory.
-
Heap memory area: Heap memory is usually divided into different areas, such as Young Generation, Old Generation and PermGen. The new generation is mainly used to store newly created objects, while the old generation is mainly used to store objects that have a long survival time. The persistent generation (in Java 8 and previous versions, replaced by metaspace after Java 8) is used to store class information and methods, etc.
-
Memory management: Java provides automatic memory management, so developers do not need to manually allocate or release memory. The Java garbage collector is responsible for handling memory allocation and recycling to ensure the correct use of memory.
-
Memory leaks: Although Java has automatic memory management, memory leaks can still occur, where objects are continuously referenced and cannot be recycled. Developers need to pay attention to promptly releasing object references that are no longer used to avoid memory leaks.
Example
Here is a simple example that shows how to create an object in Java and allocate it into heap memory:
public class HeapExample {
public static void main(String[] args) {
// 创建对象并分配到堆内存
String str = new String("Hello, World!");
// 在不再使用对象时,不要忘记将引用设为 null,以便垃圾回收
str = null;
}
}
In this example, we create a string object str
and allocate it into heap memory. When we no longer need the object, setting the reference null
to helps the garbage collector identify and reclaim objects that are no longer referenced. This is a way to prevent memory leaks.