Introduction to generics, wrapper classes and ArrayList in Java

Posted by acac on Sun, 05 Dec 2021 05:21:54 +0100

1, Generics

1.1 definition of generic class

// 1. Angle brackets < > are signs of generics
// 2. E is a type variable, and the variable name should generally be capitalized
// 3. E is a formal parameter when defined, which means the type finally passed in by MyArrayList, but it is not known yet
	public class MyArrayList<E> {
	private E[] array;
	private int size;
} 

Generic classes can have multiple type variables at a time, separated by commas.

  1. Genericity is a mechanism that works during compilation, that is, there is no concept of genericity at run time.
  2. The effect of generic code using Object during operation (not very accurate here).
  3. Meaning of generics: automatic type checking

1.2 use of generic classes

Example:

class MyArrayList<E>{//  <E> Represents that the current class is a generic class, and the E in this case is just a placeholder
    private E[] elem;
    private int usedSize;

    public MyArrayList() {
//        this.elem = elem;
        this.elem = (E[])new Object[10];//This way of writing is not very correct
    }
    public void add(E val){
        this.elem[usedSize] = val;
        usedSize++;
    }
    public E get(int pos){
        return this.elem[pos];
    }
}
public class test02 {
    public static void main(String[] args) {
        //The contents of angle brackets in generic types do not participate in the composition of types
        MyArrayList<String>  myArrayList = new MyArrayList<>();
        System.out.println(myArrayList);
        MyArrayList<Integer>  myArrayList1 = new MyArrayList<>();
        System.out.println(myArrayList1);
        MyArrayList<Boolean>  myArrayList2 = new MyArrayList<>();
        System.out.println(myArrayList2);
    }
    public static void main2(String[] args) {
        MyArrayList<String>  myArrayList = new MyArrayList<>();
        myArrayList.add("ni");//Automatically check the type. If it is not a string type, an error will be reported
        myArrayList.add("n");
        String ret = myArrayList.get(1);//Automatically cast types
        System.out.println(ret);
   }
}

1.3 generic summary

  1. Generics are introduced to solve the generality of some containers, algorithms and other codes, and can do type checking during compilation.
  2. Generics use that Object is the ancestor of all classes, and the reference of the parent class can point to the specific of the child class Object.
  3. Generics are a mechanism during compilation, that is, myarraylist < integer > and myarraylist < string > are one type at run time. That is, the contents in angle brackets in generic types do not participate in the composition of types.
  4. Generics is a legal syntax in java, marked by angle brackets < >.

2, Packaging

2.1 direct correspondence between basic data type and packaging type

Basic data typePackaging
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Basically, the first letter of the type is capitalized, except Integer and Character.

2.2 use of packaging, boxing and unboxing

Packing (packing): change the simple type into the packing type.
Unpacking: change the packaging type into a simple type.

public static void main(String[] args) {
        Integer a = 123;//Packing (implicit)
        //Range of Integer [- 128127];
        int b= a;//Unpacking (implicit)
        System.out.println("a="+a+" "+ "b="+ b);
        System.out.println("===============");
        Integer a2 = Integer.valueOf(123);//Explicit packaging
        Integer a3 = new Integer(123);//Explicit packaging

        int b2 = a2.intValue();//Explicit unpacking
        double d = a2.doubleValue();//Explicit unpacking
        int i = 10;//Explicit initialization
    }

2.3 auto boxing and auto Unboxing

In the use process, boxing and unpacking bring a lot of code, so in order to reduce the burden on developers, java provides an automatic mechanism.
Automatic boxing and unpacking are mechanisms that work during compilation.

int b2 = a2.intValue();//Explicit unpacking
double d = a2.doubleValue();//Explicit unpacking

3, Use of List

3.1 introduction to ArrayList

In the collection framework, ArrayList is a common class that implements the List interface. The specific framework diagram is as follows:

  1. ArrayList implements the RandomAccess interface, indicating that ArrayList supports random access.
  2. ArrayList implements the clonable interface, which indicates that ArrayList can clone.
  3. ArrayList implements the Serializable interface, indicating that ArrayList supports serialization.
  4. Unlike vector, ArrayList is not thread safe and can be used in a single thread. Vector or CopyOnWriteArrayList can be selected in multiple threads.
  5. The bottom layer of ArrayList is a continuous space and can be dynamically expanded. It is a dynamic type sequential table.

3.2 structure of ArrayList

public static void main(String[] args) {
	// It is recommended to create ArrayList
	// Construct an empty list
	List<Integer> list1 = new ArrayList<>();
	// Construct a list with 10 capacities
	List<Integer> list2 = new ArrayList<>(10);
	list2.add(1);
	list2.add(2);
	list2.add(3);
	// list2.add("hello"); //  Compilation failed. List < integer > has been defined. Only integer elements can be stored in List2
	// After list3 is constructed, it is consistent with the elements in list2
	//Initialize list3 with another ArrayList
    ArrayList<String> list3 = new ArrayList<>(list2);
	// Avoid omitting types, otherwise: elements of any type can be stored, and it will be a disaster when used
	List list4 = new ArrayList();
	list4.add("111");
	list4.add(100);
}

3.3 traversal of ArrayList

ArrayList can be traversed in three ways: for loop + subscript, foreach, and using iterators.

 public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("hello");
        list2.add("world");
        System.out.println(list2);//Printing mode I
        System.out.println("============");
        for (int i = 0; i < list2.size(); i++) {//Printing mode 2
            System.out.print(list2.get(i)+" ");
        }
        System.out.println();
        System.out.println("==========");
        for (String s:list2) {//Printing mode 3
            System.out.print(s+" ");
        }
        System.out.println();
        System.out.println("====Iterator print mode 1======");
       Iterator<String> it = list2.iterator();
        while (it.hasNext()){
            System.out.print(it.next()+" ");
        }
        System.out.println();
        System.out.println("=====Iterator print mode 2=====");
        ListIterator<String> it2 = list2.listIterator();//Printing method 4: use iterator to print
        while (it2.hasNext()){
            System.out.print(it2.next()+" ");
        }
    }

Output results:

3.4 common operations of ArrayList

3.4.1 delete index location element (remove)

E remove(int index) //Delete index location element

Example:

 public static void main(String[] args) {
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("hello");
        list2.add("bit");
        list2.add("haha");
        Iterator<String> it = list2.iterator();
        while (it.hasNext()) {
            String ret = it.next();
            if(ret.equals("hello")) {
                it.remove();//You need to iterate out the elements in the collection using the next method before you can call the remove method
            }else {
                System.out.print(ret + " ");
            }
        }

        System.out.println();
        System.out.println("========iterator  List Related printing==========");
        ListIterator<String> it2 = list2.listIterator();
        while (it2.hasNext()) {
            String ret = it2.next();
            if(ret.equals("hello")) {
                it2.remove();//You need to iterate out the elements in the collection using the next method before you can call the remove method
            }else {
                System.out.print(ret + " ");
            }
        }
    }

Output results:

3.4.1 add

boolean add(E e) //Tail insert e

Example:

 public static void main(String[] args) {
        ArrayList<String> list2 = new ArrayList<>();
        //CopyOnWriteArrayList<String> list2 = new CopyOnWriteArrayList<>();
        list2.add("hello");
        list2.add("bit");
        list2.add("haha");

       //Iterator iterator has no add method
       /* Iterator<String> it = list2.iterator();
        while (it.hasNext()) {
            String ret = it.next();
            if(ret.equals("hello")) {
                it.add();//No add method
            }else {
                System.out.print(ret + " ");
            }
        }*/
        
        //Adding an element using the ListIterator iterator method adds the element immediately after it
        ListIterator<String> it2 = list2.listIterator();
        while (it2.hasNext()) {
            String ret = it2.next();
            if(ret.equals("bit")) {
                it2.add("world");
           //If list2.add() is used, an exception will be thrown,
           //However, if list2 above is changed to copyonwritearraylist < string > type, no error will be reported.
            //You can use the list2.add() method
           // list2.add("world");
            }else {
                System.out.print(ret + " ");
            }
        }
        System.out.println("=================");
        System.out.println(list2);
    }

Operation results:

  ArrayList<String> list2 = new ArrayList<>();//Not thread safe
  The iteration uses it2.add("world");
 CopyOnWriteArrayList<String> list2 = new CopyOnWriteArrayList<>();//Is thread safe
  The iteration uses list2.add("world");

3.4.2 insert the element into the specified position add in the list

3.4.3 tail all elements in one ArrayList into another ArrayList (addAll)

method:

void add(int index, E element) //Insert e into the index position
boolean addAll(Collection<? extends E> c) //Trailing elements in c

Example:

public static void main(String[] args) {
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("c");
        list2.add("d");
        list2.add("d");
        System.out.println(list2);//The add method places the string at the last position of the array by default
        list2.add(0,"hello");//Add the string "hello" at the zero subscript of list2
        System.out.println(list2);
        ArrayList<String> list3 = new ArrayList<>();
        list3.add("join");
        list2.addAll(list3);//Put all the elements in list3 into list2
        System.out.println(list2);
    }

Output results:

3.4.4 delete the element remove(int index) at the specified subscript position

3.4.5 delete an element in the list for the first time remove(Object o)

3.4.6 get the element of a subscript position (get)

3.4.7 set the element of the specified subscript position to the specified value set()

method:

E remove(int index) //Delete index location element
boolean remove(Object o) //Delete the first o encountered
E get(int index) //Get subscript index position element
E set(int index, E element) //Set the subscript index position element to element

Example:

 public static void main(String[] args) {
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("c");
        list2.add("d");
        list2.add("d");
        System.out.println(list2);//The add method defaults to the last position of the array
         String ret = list2.remove(0);//Delete 0 subscript position element
        System.out.println(list2);

        boolean ret1 = list2.remove("d"); //Delete the first "d" encountered
        //If the number to be deleted is not in list2, false is returned
        System.out.println(ret1); //true
        String ret2 = list2.get(2);//Gets the element with subscript 2
        System.out.println(ret2);//d
        String ret3 = list2.set(2,"hello");//Change the element with subscript 2 to "hello"
        System.out.println(ret3);//d
        System.out.println(list2);//[b, c, hello]

Output results:

3.4.8 clear elements in linear table

3.4.9 judge whether the linear table contains an element ()

3.4.10 return the index position indexOf() of the first o

3.4.11 return the last o occurrence of the subscript position lastIndexOf()

3.4.12 intercept some elements in the partial list (sublist)

method:

void clear() //empty
boolean contains(Object o) //Judge whether o is in the linear table
int indexOf(Object o) //Returns the subscript of the first o
int lastIndexOf(Object o) //Returns the subscript of the last o
List<E> subList(int fromIndex, int toIndex) //Intercepted part list

Example:

 public static void main(String[] args) {
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("c");
        list2.add("d");
        list2.add("d");
        System.out.println(list2);//The add method defaults to the last position of the array
        System.out.println(list2.indexOf("a"));//0 determines the subscript position of a
        System.out.println(list2.lastIndexOf("d"));//4 determine the subscript position of the last d occurrence
        List<String> sub = list2.subList(1,3);//[b, c] intercept the element with subscript [1,3), and the intercepted interval range is left closed and right open
        System.out.println(sub);//[b, c]
        System.out.println(list2);//[a, b, c, d, d]
        System.out.println("===================");
        sub.set(0,"p");
        System.out.println(sub);//[p, c]
        System.out.println(list2);//[a, p, c, d, d]
       System.out.println(list2.contains("c"));//true / / judge whether list2 contains the character "c"
        list2.clear();//Empty the elements in list2
        System.out.println(list2);

Output results:

4, Capacity expansion mechanism of ArrayList

If the ArrayList calls the construction method without parameters, the size of the sequence table is 0. When it is add ed for the first time, the whole sequence table becomes 10; When the 10 is full, start to expand the capacity by 1.5 times.
If the construction method of a given capacity is called, the size of the sequence table is the given capacity. If it is full, it will be expanded by 1.5 times.

above.

Topics: Java data structure Back-end