Java learning---generics and container classes

Java learning experience

Generics

The meaning of tags in Java generics: E
- Element (used in collections, because elements are stored in collections)
T - Type (Java class)
K - Key (key)
V - Value (value)
N - Number ( numeric type)
? - Represents an undefined java type
2
1 generic method:

//泛型方法
//有限制泛型无论类与接口,关键字均为extends
class g<T extends Number> {
    
    
    public T a;
    //定义泛型类的有参构造
    public g(T a){
    
    
        this.a=a;
    }
    //定义泛型类的方法
    public T getA() {
    
    
        return a;
    }

}

public class ff {
    
    
    public static void main(String[] args) {
    
    
        //创建对象s
        g<Integer> s=new g<Integer>(10);
        System.out.println("参数为:"+s.a);
    }
}

2 Generic array:

public class ffshuzu<T> {
    
    
    private T[] a;

    public T[] getA() {
    
    
        return a;
    }

    public void setA(T[] a) {
    
    
        this.a = a;
    }

    public static void main(String[] args) {
    
    
        ffshuzu<String> s=new ffshuzu<String>();
        String[]a={
    
    "a","b","c","d","e"};
        s.setA(a);
        for (int i=0;i<a.length;i++){
    
    
            //输出数组中的每个元素
            System.out.print(s.getA()[i]+"/");
        }
    }
}

Container class

1. Java container types:
1. Java containers mainly inherit two major interfaces, namely Collection and Map.
2 The three major interfaces List, Set, and Queue inherit the Collection interface.
3 HashMap, TreeMap, LinkedHashMap, and ConcurrentHashMap inherit the Map interface.
Insert image description here
Two List implementation classes:
ArrayList: longer than random access elements, but slower when inserting and removing elements in the middle of the List;
LinkedList: it provides optimized sequential access through low-cost insertion and deletion operations in the middle of the List , relatively slow in random access, but its feature set is larger than ArrayList.

1 Comparison between Vector and ArrayList:
Vector is synchronous, so the overhead is larger than ArrayList and the access speed is slower.
Vector uses thread safety, while ArrayList is thread unsafe.
Each expansion request for Vector is 2 times its size, while for ArrayList it is 1.5 times.
2 Comparison between LinkedList and ArrayList:
ArrayList is implemented based on dynamic arrays, and LinkedList is implemented based on doubly linked lists.
ArrayList supports random access, LinkedList does not, and only supports sequential access.

Guess you like

Origin blog.csdn.net/m0_63599362/article/details/121725498