[Data Structure] Commonly used simple data structures in the Java language.

Here are some commonly used simple data structures in the Java language:

1. Array:
An array is a linear data structure used to store elements of the same type. It provides direct access to elements using indexes and has a fixed size. In Java, arrays are created with a predetermined size and can be accessed and modified using indexes.

// Creation
int[] array = new int[5]; // Creates an integer array of size 5

// Invocation
array[0] = 10; // Assigns 10 to the first element of the array
int element = array[0]; // Retrieves the value of the first element

 (关于Array最简单且不易报错的删除元素方式?注意:数组长度也改变了。我们可以设置一个新的函数removeElement来进行此操作,显然,不是很方便。)

The simplest and least error-prone way to delete an element from an array is to create a new function called removeElement that handles this operation. 

The time complexity of this function is O(n), where n is the length of the original array. In the function, we need to create a new array and copy the elements to be retained into the new array. This copying process requires iterating over all elements of the original array, resulting in a time complexity of O(n).

public class Main {
    public static void main(String[] args) {
        int[] array = {10, 20, 30, 40, 50};
        
        System.out.println("Before removal:");
        printArray(array);
        
        int[] newArray = removeElement(array, 2); // 删除索引为2的元素
        
        System.out.println("After removal:");
        printArray(newArray);
    }
    
    public static int[] removeElement(int[] array, int indexToRemove) {
        if (indexToRemove < 0 || indexToRemove >= array.length) {
            throw new IndexOutOfBoundsException("Invalid index to remove");
        }
        
        int[] newArray = new int[array.length - 1];
        
        for (int i = 0, j = 0; i < array.length; i++) {
            if (i != indexToRemove) {
                newArray[j] = array[i];
                j++;
            }
        }
        
        return newArray;
    }
    
    public static void printArray(int[] array) {
        for (int value : array) {
            System.out.println(value);
        }
    }
}

2. List:
A list is an ordered collection that allows duplicate elements. Java provides several implementations of the List interface, such as ArrayList and LinkedList. ArrayList is based on a dynamic array and LinkedList is based on a linked list. Lists offer various methods for inserting, removing, and searching for elements.

import java.util.ArrayList;
import java.util.List;

// Creation
List<String> list = new ArrayList<>(); // Creates an ArrayList of Strings

// Addition
list.add("Apple"); // Adds "Apple" to the list
list.add("Banana"); // Adds "Banana" to the list

// Deletion
list.remove("Apple"); // Removes "Apple" from the list

// Invocation
String element = list.get(0); // Retrieves the element at index 0

import java.util.LinkedList;

// Creation
LinkedList<String> linkedList = new LinkedList<>(); // Creates a LinkedList of Strings

// Addition
linkedList.add("Apple"); // Adds "Apple" to the end of the linked list
linkedList.addFirst("Banana"); // Adds "Banana" to the beginning of the linked list

// Deletion
linkedList.removeLast(); // Removes the last element from the linked list

// Invocation
String firstElement = linkedList.getFirst(); // Retrieves the first element of the linked list

 Differences: (For more details, I will put them in another post)

AspectArrayListLinkedList
Data StructureDynamic ArrayDoubly-Linked List
Random AccessEfficient (O(1))Inefficient (O(n))
Insertion/DeletionSlower for middle (O(n))Efficient at any position (O(1))
Memory OverheadHigherAdditional references and data
Use CasesFast random access, index-based operationsFrequent insertions/deletions, sequential access

3. Set:
A set is a data structure that does not allow duplicate elements(不允许重复项). Java provides different implementations of the Set interface, such as HashSet and TreeSet. HashSet is implemented using a hash table, offering fast insertion and lookup operations(why it is faster?) but does not guarantee the order of elements. TreeSet is implemented using a red-black tree(what is it and why its name is this?), which sorts the elements and provides ordered access.(For more details, I will put them in another post)

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

// Creation
Set<Integer> set = new HashSet<>(); // Creates a HashSet of Integers

// Addition
set.add(10); // Adds 10 to the set
set.add(20); // Adds 20 to the set

// Deletion
set.remove(10); // Removes 10 from the set

// Invocation
boolean containsElement = set.contains(20); // Checks if the set contains 20

import java.util.TreeSet;

// Creation
TreeSet<Integer> treeSet = new TreeSet<>(); // Creates a TreeSet of Integers

// Addition
treeSet.add(5); // Adds 5 to the tree set
treeSet.add(10); // Adds 10 to the tree set

// Deletion
treeSet.remove(5); // Removes 5 from the tree set

// Invocation
int smallestElement = treeSet.first(); // Retrieves the smallest element in the tree set

 (tree set must contain numbers or does not need to?)

4. Map:
A map is a data structure that associates key-value pairs. Java provides various implementations of the Map interface, such as HashMap and TreeMap. HashMap uses a hash table(what is a hash table?) for fast lookup and insertion of key-value pairs. TreeMap is implemented using a red-black tree(?) and sorts the key-value pairs based on the keys.(For more details, I will put them in another post)

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

// Creation
Map<String, Integer> map = new HashMap<>(); // Creates a HashMap with String keys and Integer values

// Addition
map.put("Alice", 25); // Associates the key "Alice" with the value 25
map.put("Bob", 30); // Associates the key "Bob" with the value 30

// Deletion
map.remove("Alice"); // Removes the key-value pair with the key "Alice"

// Invocation
int value = map.get("Bob"); // Retrieves the value associated with the key "Bob"

import java.util.TreeMap;

// Creation
TreeMap<String, Integer> treeMap = new TreeMap<>(); // Creates a TreeMap with String keys and Integer values

// Addition
treeMap.put("Alice", 25); // Associates the key "Alice" with the value 25
treeMap.put("Bob", 30); // Associates the key "Bob" with the value 30

// Deletion
treeMap.remove("Alice"); // Removes the key-value pair with the key "Alice"

// Invocation
int value = treeMap.get("Bob"); // Retrieves the value associated with the key "Bob"

 5. Stack:
A stack is a Last-In-First-Out (LIFO) data structure(how is it store in computer? why does it have this feature?). In Java, you can use the Stack class to implement a stack. It provides operations such as push (to add an element to the stack) and pop (to remove the top element from the stack), as well as methods to peek at the top element.

(peek v.偷看,窥视;微露出,探出 n.一瞥,偷偷地一看;(计算机)读取数据)

(For more details, I will put them in another post)

import java.util.Stack;

// Creation
Stack<String> stack = new Stack<>(); // Creates a Stack of Strings

// Addition
stack.push("Apple"); // Adds "Apple" to the stack
stack.push("Banana"); // Adds "Banana" to the stack

// Deletion
String poppedElement = stack.pop(); // Removes and returns the top element from the stack

// Invocation
String topElement = stack.peek(); // Retrieves the top element of the stack without removing it

6. Queue:
A queue is a First-In-First-Out (FIFO) data structure(?). Java offers multiple implementations of the Queue interface, such as LinkedList and ArrayDeque. LinkedList can be used as both a queue and a double-ended queue(?). ArrayDeque is an array-based(?) implementation that provides efficient insertion and removal operations(?).

(For more details, I will put them in another post)

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

// Creation
Queue<String> queue = new LinkedList<>(); // Creates a LinkedList that acts as a Queue of Strings

// Addition
queue.add("Apple"); // Adds "Apple" to the queue
queue.add("Banana"); // Adds "Banana" to the queue

// Deletion
String removedElement = queue.remove(); // Removes and returns the first element from the queue

// Invocation
String firstElement = queue.peek(); // Retrieves the first element of the queue without removing it

import java.util.ArrayDeque;

// Creation
ArrayDeque<String> arrayDeque = new ArrayDeque<>(); // Creates an ArrayDeque of Strings

// Addition
arrayDeque.add("Apple"); // Adds "Apple" to the end of the deque
arrayDeque.addFirst("Banana"); // Adds "Banana" to the beginning of the deque

// Deletion
arrayDeque.removeLast(); // Removes and returns the last element from the deque

// Invocation
String firstElement = arrayDeque.getFirst(); // Retrieves the first element of the deque

These are some commonly used simple data structures in Java. Depending on your specific needs and use cases, you can choose the appropriate data structure to store and manipulate your data.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值