New features of day16Java common object List-JDK5 (generic, enhanced for, static import, variable parameters)

New features of common objects List-JDK5

Blog name link
day16Java - Summary of common objects https://blog.csdn.net/qq_40332952/article/details/104805557

Enhanced for

New features of JDK5: Auto unpacking, generics, enhanced for, static import, variable parameters, enumeration
Enhanced for: is one of the for loops.

Format:
For (element data type variable: array or collection Collection){
Just use the variable, which is the element
}

Benefit: simplifies traversal of arrays and collections.

Disadvantage: the target of enhanced for cannot be null.
How to solve this problem? First make a non null judgment on the target of enhanced for, and then use it.

Code demo

public class NewJDK5 {
    public static void main(String[] args) {
        //Define string array
        String[] strarr = {"Grey Foss", "Lord of Shadows", "Supreme punch", "Sunset sand"};

        //Use enhanced for
        for (String s : strarr) {
            System.out.println(s);
        }
        System.out.println("--------------------------");

        //Define a collection
        List<String> list = new ArrayList<>();
        //Additive elements
        list.add("hello");
        list.add("world");
        list.add("java");
        //Use enhanced for traversal
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("--------------------------");

        ArrayList<String> list2 = null;
        //NullPointerException: error reporting null pointer exception
        // This s is obtained from list2. Before obtaining it, we should make a judgment (the goal of traversal must not be null)
        // To put it bluntly, that's what iterators do
        if (list2 != null) {
            for (String s : list2) {
                System.out.println(s);
            }
        }
        System.out.println("--------------------------");

        //Prove that enhanced for replaces iterator
        List<String> list3 = new ArrayList<>();

        list3.add("hello");
        list3.add("world");
        list3.add("java");

        //Enhanced for
        for(String s: list3){
            if("world".equals(s)){
                //ConcurrentModificationException: concurrent modification exception (this exception occurs in the iterator. If the iterator of collection modification element does not know, it will occur)
                list3.add("javase");
            }
            System.out.println(s);
        }
    }
}

Static import

Static import:
Format: import static package name . class name. Method name;
Can be imported directly to the level of the method

Precautions for static import:
A: Method must be static
B: If there are multiple static methods with the same name, it's easy to not know who to use. To use them at this time, they must be prefixed. It can be seen from this that the meaning is not great, so it is generally not needed, but it should be able to understand.

Code demo

import static java.lang.Math.abs;
import static java.lang.Math.pow;
import static java.lang.Math.max;
public class StaticImport {

    public static void main(String[] args) {
        //Complex import mode
        System.out.println(java.lang.Math.abs(-100));
        System.out.println(java.lang.Math.pow(123.45,12.43));
        System.out.println(java.lang.Math.max(20,30));
        System.out.println("-----------------------");

        //Simple import at that time
        System.out.println(Math.abs(-100));
        System.out.println(Math.pow(123.45,12.43));
        System.out.println(Math.max(20,30));
        System.out.println("-----------------------");


        //There is also a simpler way to import (static import)
        System.out.println(abs(-100));
        System.out.println(pow(123.45,12.43));
        System.out.println(max(20,30));

    }
}

Variable parameter

Variable parameter: when defining a method, you do not know how many parameters to define
Format:
Modifier return value type method name (data type Variable name) {
}

Be careful:
The variable here is actually an array
If a method has variable parameters and multiple parameters, then the variable parameter must be the last one (if it is not placed later, the previous parameters will be included by the variable parameter, and an error will be reported)
Multi parameter example:
public static int getSum(int x,int... y)
When calling a method
get(30,40,50,60,70)
The first 30 corresponds to int x by default;
All subsequent int's y

Code demo

public class ArgsDemo {
    public static void main(String[] args) {
        //Find the sum of two numbers
        int a = 10;
        int b = 20;
        System.out.println(getSum(a, b));//30

        //Find the sum of three numbers
        int c = 30;
        System.out.println(getSum(a,b,c));//60

        //By analogy, different summation parameters change, we need to write several more methods. How to write a method to meet all the needs?

        // Requirement: I want to write a function of summation. How many data summations are there? I'm not sure, but I know that I will know when I call it
        // To solve this problem, Java provides one thing: variable parameters
        int d=40;
        System.out.println(getSum(a,b,c,d));//100
        int e =50;
        System.out.println(getSum(a,b,c,d,e));//150

    }
    //Variable parameter method
    //The bottom layer is implemented by array
    public static int getSum(int... i){
        int sum = 0;

        for(int x:i){
            sum+=x;
        }
        return sum;
    }
   /* public static int getSum(int a, int b) {
        return a+b;
    }

    public static int getSum(int a, int b,int c) {
        return a+b+c;
    }*/
}

When it comes to variable parameters, it's also necessary to introduce a method in the Arrays tool class, which is to convert an array into a set (in fact, the application of variable parameters)
public static List asList(T… a) : convert an array to a set

matters needing attention:
Although you can convert an array into a set, the length of the set cannot be changed.

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

        String[] strarr = {"hello","world","java"};
        //List<String>  list = Arrays.asList(strarr);

        //The asList() method of Arrays tool class is a variable parameter application
        //List<String> list1 = Arrays.asList("hello");
        //List<String> list2 = Arrays.asList("hello","world");
        
        //Although an array can be converted into a set, the length of the set cannot be changed (that is, the returned set can be modified, but it is not allowed to add or delete)
        List<String> list3 = Arrays.asList("hello","world","java");
        
        //Unsupported Operation Exception: Unsupported Operation Exception 
        //list3.add("javaee");
        
        //Unsupported operationexception: Unsupported operation exception 
        //list3.remove(1);
        for(String s:list3){
            System.out.println(s);
        }
    }
}
221 original articles published, praised 0 and visited 5009
Private letter follow

Keywords: Java JavaEE

Added by bb_xpress on Tue, 17 Mar 2020 07:10:59 +0200