Big data Java foundation DAY19 - collection (generic, enhanced for traversal, static import, collection nesting)

catalogue

Overview and use of generics

Why are there generics?

Generic statement definition format

Benefits of generics

Generic application

Generic class

generic method

generic interface

Generic advanced (wildcard)

Overview and use of enhanced for

Enhanced for Overview

Enhanced for recycling

Overview and use of static import

Static import overview

matters needing attention

Overview and application of variable parameters

Overview of variable parameters

format

matters needing attention

A method in the Arrays tool class

Nesting of sets

Overview and use of generics

Why are there generics?

a. Introduction through case

b. Early Object types can accept any Object type, but in practical use, there will be the problem of type conversion. This hidden danger exists, so Java provides generics to solve this security problem

Generic statement definition format

< reference data type > data types in parentheses can only be reference data types

Example: create a List collection object

ArrayList<String> list = new ArrayList<>();

The generic type is String, so the collection can only add elements of String type.

Benefits of generics

a. Advance the problems in the run-time to the compilation time

b. No cast is required

c. Optimize the code and reduce the chance of error

Generic application

Generic class

Define generics on classes

Format: public class class name < generic type 1,... >

Note: generic types must be reference types

//The content in < > here only represents a parameter data type used. The parameter type enables a variable to use any name that meets the identifier rules
public class GenericTest2<A> {
    private A name;

    public void setName(A name) {
        this.name = name;
    }

    public A getName() {
        return name;
    }
}

generic method

Define generics on Methods

Format: public < generic type > return type method name (generic type.)

class Generic{
    //generic method 
    public <B> void show(B b){   //B stands for what type of data it becomes when you pass any type of data
        System.out.println(b);
    }
}
public class GenericTest3 {
    public static void main(String[] args) {
       //Create an object of Generic class
        Generic generic = new Generic();
        generic.show("sad23");      //Any type of data can be transferred
        generic.show(223);
        generic.show(2322.232);
    }
}

generic interface

Define generics on interfaces

Format: public interface interface interface name < generic type 1... >

//generic interface 
interface Generic1<C>{
    void show(C c);
}
//Create class implementation interface
class Ter<C> implements Generic1<C>{
   //Method of rewriting interface
    @Override
    public void show(C c) {
        System.out.println(c);
    }
}
//test
public class GenericTest4 {
    public static void main(String[] args) {
        //Create a Ter class object
        Ter<String> s = new Ter<>();
        s.show("sad");
    }
}

Generic advanced (wildcard)

1. Generic wildcard <? >

Any type, if not specified, is Object and any Java class

 //Generic wildcard <? > Any type, if not specified, is Object and any Java class
        ArrayList<?> list1= new ArrayList<String>();    
        ArrayList<?> list2 = new ArrayList<Integer>();
        ArrayList<?> list3 = new ArrayList<Character>();

Wildcards enable collections to hold any type of data

2.  ? extends E

Downward bound, E and its subclasses

class Teacher{}  //Create teacher class
class Student extends Teacher{}  //Create student class and inherit teacher class

public class GenericTest1 {
    public static void main(String[] args) {
          //  ?  Extensions E downward bound, E and its subclasses
        ArrayList<?extends Teacher> list1=new ArrayList<Teacher>();  //Store own type data
        ArrayList<?extends Teacher> list2=new ArrayList<Student>();  //Store subclass type data

3.  ? super E

Upward qualification, E and its parent class

 //?  super E up qualifies E and its parent classes
        ArrayList<? super Teacher> list1 = new ArrayList<Teacher>(); //Store own type data
        ArrayList<? super Teacher> list2 = new ArrayList<Object>(); //Store parent type data

Overview and use of enhanced for

Enhanced for Overview

Simplify traversal of arrays and collections

Format: for (element data type variable: array or Collection) {

Just use the variable, which is the element}

Benefits: simplified traversal

Note: the target of enhancing for should be judged whether it is null

Enhanced for recycling

Example: traversing an array

public class ForTest1 {
    public static void main(String[] args) {
        //Create a normal array
        int[] arr ={23,2,332,34};

        //Ordinary for loop traversal
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
        System.out.println("=====Dividing line=====");
        //Enhanced for loop traversal
        for (int s :arr){
            System.out.println(s);
        }
    }
}

  Similarly, you can traverse a set                                                                                                      

import java.util.ArrayList;

public class ForTest2 {
    public static void main(String[] args) {
        //Create list collection
        ArrayList<String> list = new ArrayList<>();

        //Add elements to the collection
        list.add("java");
        list.add("hive");
        list.add("bigdata");
        list.add("flink");

        //Enhance the for loop traversal, and first judge whether the collection is empty
        if (list!=null) {
            for (String s : list) {
                System.out.println(s);
            }
        }else {
            System.out.println("The collection is empty");
        }
    }
}

                                                                                                                                                                                 

Overview and use of static import

Static import overview

Format: import static package name Class name Method name;

You can import directly to the level of the method

Example: static import Math method

import static java.lang.Math.abs; //abs method of static importing Math
public class StaticTest1 {
    public static void main(String[] args) {
        //The Math method is called before it is insured.
        System.out.println(Math.abs(-233));   //Find the absolute value

        //After static import, you do not need to write the class name, but write the method name directly (for example, import static java.lang.Math.abs; at the top)
        System.out.println(abs(-233));
    }
}

 

matters needing attention

a. Method must be static

b. If there are multiple static methods with the same name, it's easy to wonder who to use? If you want to use it at this time, you must prefix it. It can be seen that it is of little significance, so it is generally not used, but it should be able to understand.

c. You can import the method you created, but the method must be static. If the name of the imported method conflicts with the method of this class, the method of this class will be called (if you still want to use the statically imported method, you need to supplement the path of the imported method package)

Example:

First create a public class

public class Static2 {
    public static void show(){
        System.out.println("Static2 Static method of");
    }
}

Then create the test class and statically import the method

import static com.shujia.ys.day19.Static2.show;  //Static import method (this is the path where I create the class)
public class StaticTest2 {
    public static void main(String[] args) {

        show();  //Although statically imported, the method name conflicts with the method name of this class, and the path needs to be supplemented
        com.shujia.ys.day19.Static2.show();
    }
    public static void show(){
        System.out.println("Static methods in this class");
    }
}

                                                                                                                                                                                                                                                                                                                                            

Overview and application of variable parameters

Overview of variable parameters

When defining a method, you don't know how many parameters to define

format

Modifier return value type method name (data type... Variable name) {}

matters needing attention

a. The variable here is actually an array

Example: create a method to sum multiple numbers

public class VarargsTest1 {
    public static void main(String[] args) {
        int a=10;
        int b=20;
        int c=30;
        int d=40;

        sum(a,c);   //Calling this method can find the sum of any number
        sum(a,c,b,d);
        sum(c,c,c);
    }
    public static void sum(int...ints){  //Create a summation method with variable parameters. The variable name ints is an array
        //Enhanced for loop traversal
            int sum=0;
        for(int i:ints){
            sum=sum+i;
        }
        System.out.println(sum);
    }
}

b. If a method has variable parameters and multiple parameters, the variable parameter must be the last one

Example: create a method to get students' arbitrary grades and

public class VarargsTest2 {
    public static void main(String[] args) {
        
        sum("student1",55,65,78);
        sum("student2",55,66,78,34);
        sum("student3",55,32);
    }
    public static void sum(String s,int...ints){  //Variable parameters are placed later
        //Enhanced for loop traversal
        int sum=0;
        for(int i:ints){
            sum=sum+i;
        }
        System.out.println(s+":"+sum);
    }
}

 

A method in the Arrays tool class

Public static < T > List < T > aslist (t... A) method of converting arrays into collections

Example:

import java.util.Arrays;
import java.util.List;

public class ArrayListTest1 {
    public static void main(String[] args) {

        //Array - > ArrayList set
        List<String> strings = Arrays.asList("java", "hive", "flink", "spark");
        //Enhanced for traversal
        for(String s:strings){
            System.out.println(s);
        }
    }
}

Nesting of sets

Example: nested implementation with list set: a school has two classes, and the traversal of students in two classes

First, encapsulate a public student class (I won't see it) Encapsulation )

public class Student2 {
    private String name;
    private int age;

    public Student2() {}
    public Student2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Then create a large set (school) and add two small sets (classes) for traversal

import java.util.ArrayList;

public class ArrayListTest2 {
    public static void main(String[] args) {
        //Create two class collections
        ArrayList<Student2> class1 = new ArrayList<>();
        ArrayList<Student2> class2 = new ArrayList<>();

        //Create student object
        Student2 s1 = new Student2("student1",18);
        Student2 s2 = new Student2("student2",22);
        Student2 s3 = new Student2("student3",20);
        Student2 s4 = new Student2("student4",19);
        Student2 s5 = new Student2("student5",21);
        Student2 s6 = new Student2("student6",20);

        //Add student object to collection
        class1.add(s1);
        class1.add(s2);
        class1.add(s3);
        class2.add(s4);
        class2.add(s5);
        class2.add(s6);

        //Create a school set and add two class sets
        ArrayList<ArrayList<Student2>> school = new ArrayList<>();
        school.add(class1);
        school.add(class2);

        //Enhance the for loop to traverse the set (the corresponding class of students cannot be seen)
        for (ArrayList<Student2> s:school){  //First traverse the class set in the school
            for (Student2 t :s){   //Then traverse the student objects in the class
                System.out.println(t.getName()+"-----"+t.getAge());
            }
        }
        System.out.println("========Dividing line==========");

        //Ordinary for loop traversal (can traverse classes separately)
        for (int i=0;i<school.size();i++){
            if (i==0){
                System.out.println("Students in class 1:");
                for (int j=0;j<school.get(i).size();j++){       //school.get(i) ==class1
                    System.out.println(school.get(i).get(j));
                }
            }else if (i==1){
                System.out.println("Students in class 2:");
                for (int j=0;j<school.get(i).size();j++){     //school.get(i) ==class2
                    System.out.println(school.get(i).get(j));
                }
            }
        }
    }
}

 

Keywords: Java Big Data IDEA

Added by mitjakac on Wed, 16 Feb 2022 15:38:57 +0200