Java Review Notes - Advanced Collections: Data Structure


Data structure overview

A data structure is a way of organizing and storing data that describes the relationships between data elements and the organization of data elements. The basic concepts of data structure include data, data elements and data items, data objects, data structures, logical structures and storage structures. Data refers to a collection of symbols that can be recognized, stored, and calculated (processed) by a computer. Data elements, also called nodes, are the basic units of data, and the smallest unit is a data item. A data object is a collection of data elements with the same characteristics and is a subset of data.

Data structure is the way computers store and organize data. It is divided into logical structure and storage structure of data. Logical structure refers to describing data in terms of logical relationships, which has nothing to do with data storage and is independent of language. Storage structure refers to how data elements and their relationships are represented when stored in the computer and depends on the language. According to the logical relationship of data, data structures can be divided into linear structures and non-linear structures. Linear structures include set structures, linear structures and bilinear structures. The elements in these structures have a one-to-one relationship with each other. Linear structures include tree structures and graph structures, and the elements in these structures have one-to-many or many-to-many relationships.

In short, data structure is a method used in computers to manage and process data, which helps improve data processing efficiency and accuracy.

Common data structures

Common data structures in Java mainly include the following:

  1. Array: An array is a linear table data structure that can store a collection of elements of the same type. In Java, arrays can be created through declaration and initialization.
  2. LinkedList: A linked list is a linear list data structure that can store collections of elements of different types. In Java, linked lists can LinkedListbe implemented through classes.
  3. Stack: The stack is a last-in-first-out (LIFO) data structure that can store collections of elements of different types. In Java, stacks can Stackbe implemented through classes.
  4. Queue: A queue is a first-in-first-out (FIFO) data structure that can store different types of element collections. In Java, queues can be implemented through Queueinterfaces and its implementation classes (such as LinkedList).
  5. Set: A set is a data structure that does not allow duplicate elements and can store collections of different types of elements. In Java, collections can be implemented through Setinterfaces and their implementation classes (such as ).HashSet
  6. Map: A map is a data structure of key-value pairs that can store collections of elements of different types. In Java, mapping can be achieved through Mapan interface and its implementation classes (such as HashMap).
  7. Tree: Tree is a non-linear data structure that can store collections of elements of different types. In Java, trees can be implemented through Treeinterfaces and its implementation classes (such as ).BinaryTree
  8. Graph: A graph is a non-linear data structure that can store collections of elements of different types. In Java, graphs can be implemented through Graphinterfaces and their implementation classes (such as ).SimpleGraph

Example

(1) Array

In Java, an array is a simple data structure used to store a fixed-size collection of elements of the same type. The following is an example of a Java array:

public class ArrayExample {
    
    
    public static void main(String[] args) {
    
    
        // 声明一个包含5个整数的数组
        int[] numbers = new int[5];

        // 通过索引访问和修改数组元素
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // 打印数组中的元素
        for (int i = 0; i < numbers.length; i++) {
    
    
            System.out.println("Element at index " + i + " : " + numbers[i]);
        }

        // 声明并初始化一个字符串数组
        String[] words = {
    
    "Hello", "World", "Java", "Array", "Example"};

        // 使用增强for循环打印数组中的元素
        for (String word : words) {
    
    
            System.out.println(word);
        }
    }
}

In this example, we first declare an array containing 5 integers numbers, and then access and modify the elements in the array by index. Next, we use a for loop to iterate through the array and print out each element. We then declared and initialized a string array wordsand used an enhanced for loop to print out the elements in the array.

(2) LinkedList

In Java, a linked list is a common data structure that is a collection of nodes. Each node contains two parts: data and a reference to the next node. Here is an example of a simple one-way linked list:

public class LinkedList {
    
    
    
    // 链表节点类
    private static class Node {
    
    
        int data;
        Node next;

        public Node(int data) {
    
    
            this.data = data;
            this.next = null;
        }
    }

    // 头节点
    private Node head;

    // 向链表添加节点
    public void add(int data) {
    
    
        Node newNode = new Node(data);
        if (head == null) {
    
    
            head = newNode;
        } else {
    
    
            Node current = head;
            while (current.next != null) {
    
    
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 打印链表
    public void printList() {
    
    
        Node current = head;
        while (current != null) {
    
    
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
    
    
        LinkedList linkedList = new LinkedList();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        linkedList.add(5);
        linkedList.printList(); // 输出:1 2 3 4 5 
    }
}

The example code above defines a simple linked list class LinkedList. It contains an inner class Nodethat represents nodes in a linked list. Each node contains an integer value and a reference to the next node. The linked list class has a head node head, which points to the first node of the linked list. addMethod is used to add a new node to the end of the linked list, while printListmethod is used to print the contents of the linked list. mainThe method creates an LinkedListobject, adds a few nodes to it, and prints out the contents of the linked list.

(3) Stack

In Java, a stack is a data structure that follows the LIFO (last in, first out) principle. This means that the last element added to the stack will be the first element removed. Java java.util.Stackclasses provide the implementation of the stack.

The following is a simple Java program that demonstrates how to use Stackclasses:

import java.util.Stack;

public class StackExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个新的Stack实例
        Stack<Integer> stack = new Stack<>();

        // 使用push方法向栈中添加元素
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println("当前栈: " + stack);

        // 使用peek方法查看栈顶元素,不移除
        int top = stack.peek();
        System.out.println("栈顶元素: " + top);
        System.out.println("执行peek操作后的栈: " + stack);

        // 使用pop方法移除栈顶元素
        top = stack.pop();
        System.out.println("被移除的元素: " + top);
        System.out.println("执行pop操作后的栈: " + stack);

        // 使用isEmpty方法检查栈是否为空
        boolean empty = stack.isEmpty();
        System.out.println("栈是否为空: " + empty);
    }
}

This example shows how to use pushmethods to add elements to the stack, peekmethods to view (but not remove) the top element of the stack, methods popto remove the top element of the stack, and isEmptymethods to check whether the stack is empty.

(4) Queue

In Java, a queue (Queue) is a special type of linear list. New elements are always added at the end of the queue, and deletion operations are always performed at the beginning of the queue. This way, elements in the queue are always first in, first out (FIFO).

The following is a simple Java program that demonstrates how to use Java's built-in Queueinterface and its implementation class LinkedList:

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个队列
        Queue<Integer> queue = new LinkedList<>();

        // 添加元素到队列
        for (int i = 1; i <= 5; i++) {
    
    
            queue.add(i);
        }

        // 显示队列的元素
        System.out.println("Elements in queue: " + queue);

        // 删除队列的头元素
        int removedElement = queue.remove();
        System.out.println("Removed element: " + removedElement);

        // 查看队列的头元素,但不删除
        int headElement = queue.peek();
        System.out.println("Head of queue: " + headElement);

        // 查看队列的大小
        int size = queue.size();
        System.out.println("Size of queue: " + size);
    }
}

In this example, we create a queue of type integer and use LinkedListthe implementation. We added some elements and displayed the contents of the queue. We then remove the queue's head element and display the queue's contents again. We also looked at the head element of the queue without removing it, and looked at the size of the queue.

This example only shows Queuethe basic functionality of Java interfaces. In actual applications, more complex operations may be used, such as priority queue (PriorityQueue) or blocking queue (BlockingQueue).

(5) Set

In Java, a Set is a collection that does not allow duplicate elements and can contain at most one null element. The following is an example of using Set in Java:

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个新的Set对象
        Set<String> set = new HashSet<>();

        // 添加元素到Set中
        set.add("A");
        set.add("B");
        set.add("C");
        set.add("D");

        // 输出Set的大小
        System.out.println("Size of set: " + set.size());

        // 检查一个元素是否在Set中
        System.out.println("Contains A? " + set.contains("A"));

        // 遍历并打印Set中的所有元素
        for (String element : set) {
    
    
            System.out.println(element);
        }

        // 删除一个元素
        set.remove("B");

        // 打印删除后的Set
        System.out.println("After removing B: " + set);
    }
}

In this example, one is created HashSet, which is Setan implementation of the interface. Then added some string elements to this Set and checked if an element exists in the Set. All elements in the Set were traversed and printed, then an element was deleted and the deleted Set was printed.

(6) Map

In Java, Map is a data structure that can store key-value pairs, where the keys are unique. Commonly used implementation classes of Map include HashMap, TreeMap, LinkedHashMap, etc. The following is an example of using Map in Java:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个新的Map对象
        Map<String, Integer> map = new HashMap<>();

        // 向Map中添加元素
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);

        // 获取Map中的元素
        int age = map.get("Bob");
        System.out.println("Bob's age is " + age);

        // 检查Map中是否包含某个键
        boolean containsKey = map.containsKey("Charlie");
        System.out.println("Map contains Charlie's key: " + containsKey);

        // 遍历Map中的所有键值对
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
    
    
            String name = entry.getKey();
            int age = entry.getValue();
            System.out.println(name + " is " + age + " years old.");
        }

        // 删除Map中的元素
        map.remove("Alice");
        System.out.println("After removing Alice: " + map);
    }
}

In this example, a HashMap is used to store people's names and corresponding ages. Some elements are added to the Map and the value of one of the elements is obtained using the get method. We also used the containsKey method to check whether the Map contains a certain key, and used the entrySet method to traverse all key-value pairs in the Map. Finally, use the remove method to delete an element in the Map.

(7) Tree

In Java, a tree is a non-linear data structure used to represent data with hierarchical relationships. Each tree consists of a root node and zero or more subtrees, each of which is also a tree. Here is a simple Java example that demonstrates how to define a basic tree structure:

// 定义一个树结构节点
class TreeNode {
    
    
    int value;
    TreeNode left;
    TreeNode right;

    // 构造方法
    TreeNode(int value) {
    
    
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

// 定义一个二叉树
public class BinaryTree {
    
    
    TreeNode root;

    // 构造方法
    BinaryTree(int value) {
    
    
        root = new TreeNode(value);
    }

    // 为了简单起见,这个例子中我们将只打印树的根节点值
    public void printRootValue() {
    
    
        System.out.println("Root Value: " + root.value);
    }

    public static void main(String[] args) {
    
    
        // 创建一个新的二叉树
        BinaryTree tree = new BinaryTree(1);

        // 打印根节点的值
        tree.printRootValue();
    }
}

In this example, a binary tree is created, which means that each node has at most two child nodes (possibly zero, that is, the node is a leaf node). Each node has a value, and references to its left and right child nodes. A method is also defined to print the value of the root node of the tree. Of course, in actual use, more methods may be needed to operate the tree, such as inserting new nodes, deleting nodes, searching for values, etc.

(8) Graph

In Java, a graph is a common data structure used to represent relationships between objects. Here is a simple example that demonstrates how to implement a graph data structure using Java:

First, the basic elements of the graph need to be defined: vertices and edges.

  1. Define vertex classes Vertex:
public class Vertex {
    
    
    private String label;
    private int index;

    public Vertex(String label, int index) {
    
    
        this.label = label;
        this.index = index;
    }

    public String getLabel() {
    
    
        return label;
    }

    public int getIndex() {
    
    
        return index;
    }
}
  1. Define edge classes Edge:
public class Edge {
    
    
    private Vertex from;
    private Vertex to;
    private int weight;

    public Edge(Vertex from, Vertex to, int weight) {
    
    
        this.from = from;
        this.to = to;
        this.weight = weight;
    }

    public Vertex getFrom() {
    
    
        return from;
    }

    public Vertex getTo() {
    
    
        return to;
    }

    public int getWeight() {
    
    
        return weight;
    }
}

Next, define a graph class Graphand implement the basic operations of the graph in it: add vertices, add edges, print graphs, etc.

  1. Define graph class Graph:
import java.util.*;

public class Graph {
    
    
    private List<Vertex> vertices;
    private List<Edge> edges;

    public Graph() {
    
    
        vertices = new ArrayList<>();
        edges = new ArrayList<>();
    }

    public void addVertex(Vertex vertex) {
    
    
        vertices.add(vertex);
    }

    public void addEdge(Edge edge) {
    
    
        edges.add(edge);
    }

    public void printGraph() {
    
    
        System.out.println("Vertices:");
        for (Vertex vertex : vertices) {
    
    
            System.out.println("Label: " + vertex.getLabel() + ", Index: " + vertex.getIndex());
        }
        System.out.println("Edges:");
        for (Edge edge : edges) {
    
    
            System.out.println("From: " + edge.getFrom().getLabel() + ", To: " + edge.getTo().getLabel() + ", Weight: " + edge.getWeight());
        }
    }
}

Now, you can create a graph and operate on it:

  1. Main class Main:
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Graph graph = new Graph();
        Vertex v1 = new Vertex("A", 0);
        Vertex v2 = new Vertex("B", 1);
        Vertex v3 = new Vertex("C", 2);
        graph.addVertex(v1);
        graph.addVertex(v2);
        graph.addVertex(v3);
        graph.addEdge(new Edge(v1, v2, 1));
        graph.addEdge(new Edge(v2, v3, 2));
        graph.addEdge(new Edge(v3, v1, 3));
        graph.printGraph();
    }
}

In this example, a simple undirected graph is created with three nodes A, B, and C, and three edges connecting them. The edge weights represent the distance from A to B as 1, the distance from B to C as 2, and the distance from C to A as 3. These weights can be interpreted as the distance between any two nodes, for example, the distance between node A and node B is 1, the distance between node B and node C is 2, and so on.

To fully represent this graph, an adjacency matrix can be used to represent it. The adjacency matrix is ​​a two-dimensional array in which rows and columns represent nodes in the graph. The elements in the matrix represent whether there is an edge connecting two nodes and the weight of the edge. In this example, the adjacency matrix can look like this:

A B C
A 0 1 3
B 1 0 2
C 3 2 0

The element in the first row and the second column is 1, which means there is an edge with a weight of 1 from A to B; the element in the second row and the third column is 2, which means there is an edge from B to C with a weight of 2; with And so on.

In addition to adjacency matrices, adjacency lists can also be used to represent graphs. An adjacency list is an array in which each element represents a node and its adjacent nodes and edges. For example, for the graph above, the adjacency list could look like this:

A: B(1) C(3)
B: A(1) C(2)
C: A(3) B(2)

The first element A in the first line represents the starting node, followed by a colon followed by its adjacent nodes and the corresponding edge weights. For example, there is an edge from A to B with weight 1, and there is an edge from A to C with weight 3. By analogy, the same is true for other nodes.

おすすめ

転載: blog.csdn.net/m0_62617719/article/details/132917270