[java] Summary of java notes - java API | generics | collection framework

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

、java API

1.1. Concept

The Java API (Application Programming Interface) provides many pre-built classes, interfaces, and exception handling methods for developing Java applications. These classes and interfaces are designed to accomplish specific tasks, such as:

File I/O (such as File, InputStream, OutputStream, etc.)

Network programming (such as Socket, ServerSocket, etc.)

Database connection (JDBC)

User interface components (Swing or JavaFX)

Collection classes (such as List, Set, Map, etc.)

Multi-thread processing (such as Thread, Runnable, etc.)

Data and time processing, etc. (such as LocalDate, LocalTime, etc.)

All these classes and interfaces are organized according to related packages (package), which makes it easy for developers to find the classes or interfaces they need. Using Java API, developers can avoid writing all codes from scratch, thus improving development efficiency and code quality.

1.2、java.lang

java.lang is the core package of the Java programming language (Package), which provides the most basic and core classes of Java programs. The classes and interfaces in this package will be automatically imported into all Java programs, without the need for developers to manually import them.
The java.lang package contains many important classes such as:

Object: This is the root class of the class hierarchy from which all classes inherit.

String: Used to create and manipulate strings.

StringBuilder and StringBuffer: used to create modifiable strings.

Math: Provides methods to perform basic mathematical operations, such as square root, absolute value, etc.

System: Provides system-level functions such as accessing environment variables, input and output streams, and loading files.

Thread: used to create and manipulate threads to achieve multi-threaded programming.

Exception, Error, etc.: Used to handle and define errors and exceptions.

There are also some basic packaging types, such as Integer, Long, Double, Boolean, etc., which are defined in the java.lang package. These wrapper classes provide class-level functionality for primitive data types.
Overall, the java.lang package provides the basic classes and interfaces necessary to write Java programs.


Now that the eight major data types of java are available, do we need to create their encapsulation classes?
Java provides corresponding wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, Boolean) for its 8 basic data types (byte, short, int, long, float, double, char, boolean). There are several main reasons for doing this:

Object operations: Primitive data types are primitive types, not objects. Sometimes we need to treat them as objects, for example in generics, collections framework, only objects can be used.

Null means: primitive data types cannot be null, while their wrapper classes can. This is useful for representing situations where a value might not exist.

Utility methods: The wrapper class provides some utility methods, such as converting a string to a number, judging whether a character is a number, and so on.

Default values ​​of class members: member variables of classes have default values, basic types have their own default values ​​(such as the default value of int is 0), and the default value of objects is null. Use wrapper types to distinguish between uninitialized and default values.

Autoboxing and unboxing: Java 5 introduced autoboxing and unboxing features that allow programmers to automatically or implicitly convert between primitive data types and their corresponding wrapper classes.

For example:

List<Integer> list = new ArrayList<>();
list.add(5);  // 这里发生自动装箱,将 int 类型的 5 装箱成 Integer 类型

int number = list.get(0);  // 这里发生自动拆箱,将 Integer 类型拆箱为 int 类型

Wrapper classes are very useful in Java programming because they allow more flexible and advanced operations and representations.


The difference between java.lang.Math and java.math
java.lang.Math and java.math are two different packages in Java, and their functions and usage scenarios are different.

java.lang.Math: This is a class in Java's core class library that provides a series of static methods for performing basic mathematical operations, such as trigonometric functions, logarithms, powers, square roots, and so on. It also provides methods for generating random numbers, rounding, etc. Since this class is in the java.lang package, it can be used in any Java program without manual import.

java.math: This is a package that contains classes ( such as BigInteger and BigDecimal ) for performing mathematical operations beyond the limits of primitive number types (such as int, long, double). For example, when you need to perform very large integer calculations, or high-precision floating-point calculations, you need to use the classes in this package. These classes provide a series of methods to perform operations such as addition, subtraction, multiplication, and division.

To sum up, java.lang.Math provides basic mathematical operations, while java.math provides more advanced mathematical functions beyond the limitations of primitive types.


What does the java.util package do?
java.util is a package in Java that contains many utility classes and interfaces, mainly used to implement data structures, algorithms, and time and date processing. The following are some of the main classes and interfaces in the java.util package:

Collection-related classes and interfaces: such as List, ArrayList, LinkedList, Set, HashSet, TreeSet, Map, HashMap, TreeMap, etc. These classes and interfaces are used to store and manipulate data.

Date and time related classes: such as Date, Calendar, TimeZone, etc. These classes are used to represent and manipulate dates and times.

Other utility classes: such as Random (for generating random numbers), Timer and TimerTask (for scheduling tasks), Observable and Observer (for implementing the observer pattern), etc.

Enumeration classes: such as Enumeration, Iterator, and ListIterator, which are used to enumerate (traverse) data collections.

Functional Interface: New features introduced by Java 8, such as Function, Consumer, Predicate, etc., which are very useful when doing functional programming.

The java.util package is a package that is often used when writing Java programs, and it provides many important data structures and algorithms

Two, generic

2.1. Concept

Java generics is a new feature introduced by JDK 5.0, which is mainly used for type safety of code and elimination of type coercion.

Type safety: The main goal of generics is to improve the type safety of Java programs. By knowing what type of object a generic collection will receive, the compiler can ensure at compile time that the correct type of object is used for the method call, reducing runtime errors.

Eliminate type conversions: In generics, you don't need type conversions. You can treat objects of one type as another type, and the runtime type checking and automatic type conversion will be done by the compiler.

I can provide you with a few examples of generics in Java:
Example 1: Generic class

public class Box<T> {
    
    
    private T t;

    public void set(T t) {
    
     this.t = t; }
    public T get() {
    
     return t; }
}

Box<Integer> integerBox = new Box<>();
integerBox.set(123);

Box<String> stringBox = new Box<>();
stringBox.set("Hello World");

In the above code, Box is a generic class that can be used to store various types of objects. When creating a Box object, we need to specify the type of storage.
Example 2: Generic Interface

interface Pair<K, V> {
    
    
    public K getKey();
    public V getValue();
}

class OrderPair<K, V> implements Pair<K, V> {
    
    
    private K key;
    private V value;

    public OrderPair(K key, V value) {
    
    
        this.key = key;
        this.value = value;
    }

    public K getKey() {
    
     return key; }
    public V getValue() {
    
     return value; }
}

OrderPair<String, Integer> p1 = new OrderPair<>("Even", 8);
OrderPair<String, String>  p2 = new OrderPair<>("hello", "world");

In this example, Pair is a generic interface with two type parameters, and the OrderPair class implements this interface.
Example 3: Generic Method

public class Util {
    
    
    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
    
    
        return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue());
    }
}

Pair<Integer, String> p1 = new OrderPair<>(1, "apple");
Pair<Integer, String> p2 = new OrderPair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);

In this example, Util.compare() is a generic method that can be used to compare any type of Pair object.
These examples demonstrate the flexibility of Java generics, and using them can help you write more generic and safer code.

2.2. Similarities and differences between generics in java and C++ templates

Java's generics and C++'s templates are similar in many respects. They both provide a way to write generalized code so that various types of data can be processed, rather than writing separate codes for each type. This facilitates code reuse and type safety.
However, they have some important differences in implementation and functionality:

Compile time: In C++, templates are instantiated at compile time. When you use a template of a particular type, the compiler generates a new template instance for that type. This means that if you use templates with many different types, the compiled code can become quite large.
In contrast, Java's generics are implemented using type erasure. This means that at compile time, all generic information is removed, leaving only primitive types. This can make the generated bytecode smaller, but also means that some type information is not available at runtime.

Function: C++ templates are more powerful, they can be used for classes, functions and variables, and support template specialization and partial specialization. This allows templates to be used for very complex and advanced programming techniques.
In contrast, Java's generics are mainly used for classes and methods, and their functions are relatively simple. The main purpose of generics in Java is to improve type safety and code readability, not to provide advanced programming skills.

In general, although Java's generics and C++'s templates are conceptually similar, they have some important differences in their implementation and usage.

3. Collection framework

3.1. Concept

The Java Collections Framework provides a set of classes and interfaces for storing and managing data. This framework mainly includes interfaces, implementations (classes) and algorithms.

Main interfaces: mainly Collection, List, Set, Queue, Deque, Map, etc. These interfaces respectively define the behavior that various collections should have. For example, a List is an ordered, repeatable collection, while a Set is an unordered, non-repeatable collection.

Main implementations: ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap, etc. These classes provide various types of data structures such as dynamic arrays, linked lists, hash tables, trees, etc.

Algorithms: These are static methods, mainly in the Collections class, that provide various operations such as sorting, searching, synchronization control, etc.

Here is a brief overview of these main interfaces and implementations:

List interface: an ordered, repeatable collection. For example, ArrayList and LinkedList are common implementations of this interface. ArrayList is implemented based on a dynamic array, which is fast to search but slow to add and delete; LinkedList is implemented based on a doubly linked list, which is fast to add and delete but slow to search.

Set interface: an unordered, non-repeatable collection. For example, HashSet, LinkedHashSet, and TreeSet. HashSet is implemented based on a hash table and has a fast access speed; TreeSet is implemented based on a red-black tree, and its elements are ordered; LinkedHashSet maintains a doubly linked list that runs on all entries, providing order.

Map interface: a collection of key-value pairs. For example, HashMap, TreeMap, and LinkedHashMap. HashMap provides fast query, but without any order; TreeMap is sorted by key; LinkedHashMap maintains the order of key insertion.

Queue and Deque interfaces: queues and double-ended queues. For example, LinkedList, ArrayDeque, PriorityQueue, etc. LinkedList and ArrayDeque can be used as queues or double-ended queues; PriorityQueue is a priority queue, and the elements will be sorted according to the natural order or the provided comparator.

This is just a brief overview of the collection framework. In actual use, you need to choose the appropriate collection type according to your specific needs. Also, most collection classes support generics and can be used to store objects of any type.

3.2. Collection interface

In Java, Collection is the basic interface of the Java collection framework, which is the parent interface of the List, Set, and Queue interfaces. This interface declares common methods for storing a set of objects.
These methods include:

add(E e): Make sure this collection contains the specified element.

addAll(Collection<? extends E> c): Adds all elements in the specified collection to this collection.

clear(): Removes all elements in this collection.

contains(Object o): Returns true if this collection contains the specified element.

containsAll(Collection<?> c): Returns true if this collection contains all elements in the specified collection.

isEmpty(): Returns true if this collection contains no elements.

iterator(): Returns an iterator over the elements in this collection.

remove(Object o): Removes the specified element from this collection, if present.

removeAll(Collection<?> c): Removes all elements in this collection that are contained in the specified collection.

retainAll(Collection<?> c): Retains only elements in this collection that are contained in the specified collection.

size(): Returns the number of elements in this collection.

toArray(): Returns an array containing all elements in this collection.

Note that the Collection interface itself does not support direct access to elements, or does not provide a method for obtaining elements at a specified location, which is provided by its subinterface List. For unordered collections (such as Set), the position of the elements has no practical significance, so the Collection interface does not provide a method for direct access to the elements.
When you need a collection, you generally use a subinterface of the Collection interface, such as List, Set, or Queue, which provide more specific behavior. For each sub-interface, Java provides some implementation classes, such as ArrayList, HashSet, LinkedList, etc.

3.3. List interface

In Java, the List interface is an important sub-interface of the Collection interface, which represents an ordered and repeatable collection of elements.
The List interface defines some list-specific operations, such as accessing elements by positional index, searching for elements, iterating lists, etc. Here are some important methods of the List interface:

void add(int index, E element): Insert the specified element at the specified position of the list.

boolean add(E e): Appends the specified element to the end of this list.

E get(int index): Returns the element at the specified position in the list.

int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

ListIterator listIterator(): Returns a list iterator over the elements of this list (in proper order).

E remove(int index): Remove the element at the specified position in this list.

E set(int index, E element): Replaces the element at the specified position in this list with the specified element.

The List interface has several commonly used implementation classes, including ArrayList, LinkedList, and Vector.

ArrayList: Based on a dynamic array implementation, it provides fast random access, but the speed of inserting and deleting elements in the middle of the list is relatively slow.

LinkedList: Based on a doubly linked list implementation, it provides fast insertion and deletion operations, but the speed of random access is slow.

Vector: Similar to ArrayList, but it is synchronized and can be used in a multi-threaded environment, but its performance will be slower than ArrayList.

Which implementation class to choose depends on your specific needs. For example, if you need to access elements frequently, ArrayList is a good choice; if you need to insert and delete elements frequently, then LinkedList may be more suitable.

3.4. Set interface

In Java, the Set interface is a subinterface of the Collection interface, which represents a collection that does not contain duplicate elements. That is, each element can only appear once.
The main methods of the Set interface are inherited from Collection, and no new methods have been added, but it has several important implementation classes, including HashSet, LinkedHashSet and TreeSet, which provide various types of behaviors:

HashSet: Based on the hash table implementation, this is the most commonly used Set implementation class. It does not guarantee the order of elements, allows the use of null elements, and provides the ability to quickly access elements.

LinkedHashSet: maintains a doubly linked list that runs on all entries, so it can output the insertion order of elements. Compared to HashSet, its iteration performance is better, but it is slightly slower when inserting and deleting elements.

TreeSet: Based on the implementation of red-black tree (a self-balancing binary search tree), the elements will be sorted in ascending order (if a custom comparison function is added, it can also be sorted in a custom order), but the access and operation The time complexity is O(log(n)).

Note that although the Set interface inherits the add, remove, and contains methods of the Collection interface, the behavior of the Set is different from the Collection, especially for the add method. When you try to add an element that already exists in the Set, the add method will return false, and the Set will not be changed, while Collection will allow duplicate elements to be added.

3.5. Map interface

In Java, the Map interface is not a sub-interface of the Collection interface. It represents a mapping relationship and can store key-value pairs. Both keys and values ​​can be any type of object, keys cannot be duplicated, but values ​​can.
The Map interface defines some methods for manipulating key-value pairs, as follows:

void clear(): Remove all mappings.

boolean containsKey(Object key): Returns true if this map contains a mapping for the specified key.

boolean containsValue(Object value): Returns true if this map maps one or more keys to the specified value.

Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the mappings contained in this map.

V get(Object key): Returns the value mapped by the specified key; if the map does not contain the mapping relationship of the key, it returns null.

boolean isEmpty(): Returns true if this map contains no key-value mappings.

Set keySet(): Returns a Set view of the keys contained in this map.

V put(K key, V value): Associates the specified value with the specified key in this map.

void putAll(Map<? extends K, ? extends V> m): Copies all mappings from the specified map into this map.

V remove(Object key): If there is a mapping relationship for a key, remove it from this mapping.

int size(): Returns the number of key-value mappings in this map.

Collection values(): Returns a Collection view of the values ​​contained in this map.

The Map interface has some common implementation classes, including HashMap, LinkedHashMap, TreeMap, and Hashtable:

HashMap: Based on the implementation of the hash table, this is the most commonly used Map implementation class. It does not guarantee the order of the map, allowing null values ​​and null keys.

LinkedHashMap: maintains a doubly linked list that runs on all entries, so the map can be iterated in insertion order or access order (LRU).

TreeMap: Based on a red-black tree (a self-balancing binary search tree), it sorts all key-value pairs according to the natural order of the keys or the Comparator provided at creation time.

Hashtable: Similar to HashMap, but does not allow null keys and null values, and is synchronized.

When choosing which Map implementation class to use, you need to consider your needs, such as whether you need to sort, whether you allow null keys and values, and whether you need to consider more

Guess you like

Origin blog.csdn.net/weixin_46274756/article/details/131276214