Collection Sets and Generics

Keywords: Java

Chapter 1 Collection Sets

1. Sets and arrays

What is the difference between sets and arrays?
    A. Length
    	a. The length of the array is fixed and cannot be changed during operation.
    	b. The length of the collection is variable and can be added or deleted.
    B. Contents
    	Arrays can store any type (basic data type and reference data type) 
    		//int[] arr1 = new int[3];   
    		// Student[] stuArr = new Student[3]; object array
    	b. Collections can only store object type data
    		// ArrayList < String > LIST1 = new ArrayList <>(); // string object
    		// ArrayList < Integer > List2 = new ArrayList <>(); // Stores Integer objects, automatically Boxed
    		
Recommended usage:
	Later courses, recommended use of collections
	// Arrays are intended only to derive collections and to refer to the characteristics of data types (address values and default values)

2. Common methods of sets

1. increase
	public abstract boolean add(E e); //Adding elements
2. Delete
	public abstract boolean remove(Object o); //Delete an element
	public abstract void clear(); //Delete all elements
3. change
	public abstract Object[] toArray();  //Converting a collection to an array of Object types
	public abstract <T> T[] toArray(T[] a); //Converting a collection into a specific type of array
4. check
	public abstract boolean contains(Object o);  //Check to see if an element is included
	public abstract boolean isEmpty(); //Judge whether it is empty
	public abstract int size(); //Gets the length and size of the collection and the number of elements to store

3. Concurrent modification exception

1. Concurrent modification exception
	Name: Concurrent ModificationException
	Reason: In the process of traversing collections with iterators, adding and deleting collections data can lead to concurrent modification exceptions.
	Solution: Do not randomly add or delete data during iterator traversal
	
2. Life Example - > "Modifying Needs"
	"Decorate the house." Please help me decorate the house. Halfway through the decoration, suddenly I said I would change to XXX style.
    "Frequently modify requirements in the process of doing projects"

4. Three traversal modes of sets

public static void main(String[] args) {
    //The left parent and right child of the object creating the collection are polymorphic
    Collection<String> c = new ArrayList<>();
    //Add data
    c.add("Dili Reba");
    c.add("Gulinaza");
    c.add("Malzahar");
    c.add("Leather sofa");
    System.out.println("======= [1]Mode 1:Array of rotation ====");
    //Define an array whose type is consistent with the generic type of the collection
    String[] arr = new String[c.size()];
    c.toArray(arr); //Array of rotation
    for (int i = 0; i < arr.length; i++) {
        System.out.println(arr[i]);
    }
    System.out.println("======= [2]Mode 2:iterator ====");
    //Shortcut key it itit
    Iterator<String> iter = c.iterator();
    while (iter.hasNext()) {
        String next = iter.next();
        System.out.println(next);
    }
    System.out.println("======= [3]Mode 3:Enhance for ===");
    //Shortcut Set Name. for Enter c.for
    for (String s : c) {
        System.out.println(s);
    }
}

Chapter II Generics

1. The Concept of Generics

1. Why use generics?
	I know there is a data type here, but I don't know exactly what type it is, so I use generics instead.
	
2. For example:
	ArrayList knows that he can store objects. But it's not clear what objects need to be stored.
	As the author of the ArrayList class. When Josh Bloch designs classes, they are defined as generics, and the user (Java programmer) specifies the type.
	
3. What are the benefits of generics?
	A. Benefits:
		a. Raise runtime exceptions to compile time. // For example, the add method of ArrayList can be validated when storing data using generics
        b. Avoid type conversion exceptions. // Type conversion exception, ClassCastException that occurs during downward transition
    B. Disadvantages:
		When I first started writing code, it was a bit of a hassle. // For example, when creating an object in ArrayList, you need to write an angle bracket and a specific type.

2. Generic Classes

Definition of generic class
//Adding angle brackets after a class is generic
//Definition of generic class
public class Car<NIUBEA> {
    //Define variables
    private NIUBEA nb;

    public NIUBEA getNb() {
        return nb;
    }

    public void setNb(NIUBEA nb) {
        this.nb = nb;
    }
}
Use of generic classes
//Test class
//Use of generic classes
public class Test {
    public static void main(String[] args) {
        //Think about it: How does ArrayList use generics?
        //When creating an object, specify the specific data type
        Car<String> c1 = new Car<>();
        c1.setNb("Maserati");
        String nb1 = c1.getNb();
        System.out.println("nb1 = " + nb1); //nb1 = Maserati
        System.out.println("===========================");
        //When creating an object, specify the specific data type
        Car<Double> c2 = new Car<>();
        c2.setNb(288.88);
        Double nb2 = c2.getNb();
        System.out.println("nb2 = " + nb2); //nb2 = 288.88
    }
}

3. Generic Method

Definition of generic methods
//Dog Bar
//Definition of generic methods
public class DogBa {
    //Defining generic methods
    public static <HEHE> void method(HEHE hehe){
        //Print information
        System.out.println(hehe);
        //Object to get bytecode
        System.out.println(hehe.getClass());
    }
}
Use of generic methods
//Test class
//Use of generic methods
public class Test {
    public static void main(String[] args) {
        DogBa.method("Hey,Can you see me??");
        //Hey hey, can you see me?
        //class java.lang.String
        System.out.println("===========================");
        DogBa.method(666);
        //666
        //class java.lang.Integer
        System.out.println("===========================");
        DogBa.method(3.14F);
        //3.14
        //class java.lang.Float
    }
}

4. Generic Interface

Definition of generic interfaces
//Animal interfaces. generic interfaces
public interface IAnimal<SUIBIAN> {
    //The abstract method of definition
    public abstract void eat(SUIBIAN sb);
}
Use of generic interfaces
//Usage 1: Change son into generic class, specify specific type when creating son object
public class Ma<SUIBIAN> implements IAnimal<SUIBIAN> {
    @Override
    public void eat(SUIBIAN sb) {
        System.out.println(sb);
        System.out.println(sb.getClass());
    }
}
//Usage Mode 2: Turn Sons into Specific Types
public class Lu implements IAnimal<String>{
    @Override
    public void eat(String sb) {
        System.out.println(sb);
        System.out.println(sb.getClass());
    }
}
//Test class
public class Test {
    public static void main(String[] args) {
        //Way 1: When creating subclasses/implementing class objects, specify specific types
        Ma<String> make = new Ma<>();
        make.eat("pineapple");
        //pineapple
        //class java.lang.String
        System.out.println("-----");
        Ma<Integer> madongmei = new Ma<>();
        madongmei.eat(666);
        //666
        //class java.lang.Integer
        System.out.println("==========");
        //Way 2: Create the object of the implementation class directly, and the implementation class has specified the specific type.
        Lu luhan = new Lu();
        luhan.eat("Meal");
        //Meal
        //class java.lang.String
    }
}

5. Generic wildcards

1. What is the wildcard?
    When you don't know exactly what generics are, use generic wildcards?
    Mainly used in methods. // I don't know what the specific generics in List are. Can I use them instead?
    For example: public static void printList (List <?> list) {...}  

2. The upper and lower limits of generics, Integer extends Number extends Object // / whether upper or lower limits, can be passed in by themselves
	A. Upper limit: either son or self
		 public static void printList(List<? extends Number> list){ .... }  
		// Here you can pass in Number and its subclasses (NumberInteger)
	B. Lower Limit: Father or self
		public static void printList(List<? super Number> list){ .... }  
		// What you can pass in is Number and Number's parent class (Number Object)

Posted by crondeau on Sat, 24 Aug 2019 06:08:28 -0700