Beginners want to learn java

1. Packaging

1.1 basic type packaging (memory)

  • Function of basic type packaging class

    The advantage of encapsulating a basic data type as an object is that more functional methods can be defined in the object to manipulate the data

    One of the common operations: used for conversion between basic data type and string

  • Wrapper class corresponding to basic type

    Basic data typePackaging
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    doubleDouble
    charCharacter
    booleanBoolean

1.2Integer class (application)

  • Overview of Integer class

    Wrap the value of the original type int in an object

  • Integer class constructor

    Method nameexplain
    public Integer(int value)Create Integer object based on int value (obsolete)
    public Integer(String s)Create Integer object based on String value (obsolete)
    public static Integer valueOf(int i)Returns an Integer instance representing the specified int value
    public static Integer valueOf(String s)Returns an Integer object String that holds the specified value
  • Sample code

    public class IntegerDemo {
        public static void main(String[] args) {
            //public Integer(int value): creates an Integer object based on the int value (obsolete)
            Integer i1 = new Integer(100);
            System.out.println(i1);
    
            //public Integer(String s): creates an Integer object based on the String value (obsolete)
            Integer i2 = new Integer("100");
    //        Integer i2 = new Integer("abc"); //NumberFormatException
            System.out.println(i2);
            System.out.println("--------");
    
            //public static Integer valueOf(int i): returns an Integer instance representing the specified int value
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //public static Integer valueOf(String s): returns an Integer object String that holds the specified value
            Integer i4 = Integer.valueOf("100");
            System.out.println(i4);
        }
    }
    

1.3 mutual conversion of int and String types (memory)

  • Convert int to String

    • Conversion mode

      • Method 1: add an empty string directly after the number
      • Method 2: use the String class static method valueOf()
    • Sample code

      public class IntegerDemo {
          public static void main(String[] args) {
              //int --- String
              int number = 100;
              //Mode 1
              String s1 = number + "";
              System.out.println(s1);
              //Mode 2
              //public static String valueOf(int i)
              String s2 = String.valueOf(number);
              System.out.println(s2);
              System.out.println("--------");
          }
      }
      
  • Convert String to int

    • Conversion mode

      • Method 1: first convert the string number to Integer, and then call the valueOf() method
      • Method 2: convert through Integer static method parseInt()
    • Sample code

      public class IntegerDemo {
          public static void main(String[] args) {
              //String --- int
              String s = "100";
              //Method 1: String --- Integer --- int
              Integer i = Integer.valueOf(s);
              //public int intValue()
              int x = i.intValue();
              System.out.println(x);
              //Mode 2
              //public static int parseInt(String s)
              int y = Integer.parseInt(s);
              System.out.println(y);
          }
      }
      

1.4 string data sorting case (application)

  • Case requirements

    There is a string: "91 27 46 38 50". Please write a program to realize it. The final output result is: "27 38 46 50 91"

  • code implementation

    public class IntegerTest {
        public static void main(String[] args) {
            //Define a string
            String s = "91 27 46 38 50";
    
            //Store the numeric data in the string into an array of type int
            String[] strArray = s.split(" ");
    //        for(int i=0; i<strArray.length; i++) {
    //            System.out.println(strArray[i]);
    //        }
    
            //Define an int array and store each element in the String [] array in the int array
            int[] arr = new int[strArray.length];
            for(int i=0; i<arr.length; i++) {
                arr[i] = Integer.parseInt(strArray[i]);
            }
    
            //Sort int array
            Arrays.sort(arr);
    
            //The elements in the sorted int array are spliced to obtain a string, which is implemented by StringBuilder
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<arr.length; i++) {
                if(i == arr.length - 1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(" ");
                }
            }
            String result = sb.toString();
    
            //Output results
            System.out.println(result);
        }
    }
    

1.5 automatic unpacking and automatic packing (understanding)

  • Automatic packing

    Convert the basic data type to the corresponding wrapper class type

  • Automatic unpacking

    Convert the wrapper class type to the corresponding basic data type

  • Sample code

    Integer i = 100;  // Automatic packing
    i += 200;         // i = i + 200;  i + 200 automatic unpacking; i = i + 200;  It's automatic packing
    

2. Time and date

2.1Date class (application)

  • Overview of Date class

    Date represents a specific time, accurate to milliseconds

  • Date class constructor

    Method nameexplain
    public Date()Allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
    public Date(long date)Allocates a Date object and initializes it to represent the specified number of milliseconds from the standard base time
  • Sample code

    public class DateDemo01 {
        public static void main(String[] args) {
            //public Date(): allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
            Date d1 = new Date();
            System.out.println(d1);
    
            //public Date(long date): allocate a Date object and initialize it to represent the specified number of milliseconds from the standard base time
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

2.2 common methods of date class (application)

  • common method

    Method nameexplain
    public long getTime()Gets the millisecond value of the date object from 00:00:00, January 1, 1970 to the present
    public void setTime(long time)Set the time and give the value of milliseconds
  • Sample code

    public class DateDemo02 {
        public static void main(String[] args) {
            //Create date object
            Date d = new Date();
    
            //public long getTime(): gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
    //        System.out.println(d.getTime());
    //        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year");
    
            //public void setTime(long time): sets the time. The value given is milliseconds
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

2.3 simpledateformat class (application)

  • SimpleDateFormat class overview

    SimpleDateFormat is a concrete class for formatting and parsing dates in a locale sensitive manner.

    We focus on date formatting and parsing

  • SimpleDateFormat class constructor

    Method nameexplain
    public SimpleDateFormat()Construct a SimpleDateFormat, using the default mode and date format
    public SimpleDateFormat(String pattern)Construct a SimpleDateFormat using the given pattern and the default date format
  • Common methods of the SimpleDateFormat class

    • Format (from Date to String)
      • public final String format(Date date): formats the date into a date / time string
    • Parsing (from String to Date)
      • public Date parse(String source): parses text from the beginning of a given string to generate a date
  • Sample code

    public class SimpleDateFormatDemo {
        public static void main(String[] args) throws ParseException {
            //Format: from Date to String
            Date d = new Date();
    //        SimpleDateFormat sdf = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //From String to Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

2.4 date tool case (application)

  • Case requirements

    Define a date tool class (DateUtils), which contains two methods: convert the date to a string in the specified format; Parse the string into a date in the specified format, and then define a test class (DateDemo) to test the methods of the date tool class

  • code implementation

    • Tool class
    public class DateUtils {
        private DateUtils() {}
    
        /*
            Converts the date to a string in the specified format
            Return type: String
            Parameters: date, date, string format
         */
        public static String dateToString(Date date, String format) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            String s = sdf.format(date);
            return s;
        }
    
    
        /*
            Parses the string to a date in the specified format
            Return value type: Date
            Parameters: String s, String format
         */
        public static Date stringToDate(String s, String format) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date d = sdf.parse(s);
            return d;
        }
    
    }
    
    • Test class
    public class DateDemo {
        public static void main(String[] args) throws ParseException {
            //Create date object
            Date d = new Date();
    
            String s1 = DateUtils.dateToString(d, "yyyy year MM month dd day HH:mm:ss");
            System.out.println(s1);
    
            String s2 = DateUtils.dateToString(d, "yyyy year MM month dd day");
            System.out.println(s2);
    
            String s3 = DateUtils.dateToString(d, "HH:mm:ss");
            System.out.println(s3);
            System.out.println("--------");
    
            String s = "2048-08-09 12:12:12";
            Date dd = DateUtils.stringToDate(s, "yyyy-MM-dd HH:mm:ss");
            System.out.println(dd);
        }
    }
    

2.5Calendar class (application)

  • Calendar Class overview

    Calendar provides some methods for the conversion between a specific moment and a set of calendar fields, and some methods for manipulating calendar fields

    Calendar provides a class method, getInstance, to get commonly useful objects of this type.

    This method returns a Calendar object.

    Its calendar field has been initialized with the current date and time: calendar rightnow = calendar getInstance();

  • Common methods of Calendar Class

    Method nameexplain
    public int get(int field)Returns the value of the given calendar field
    public abstract void add(int field, int amount)Add or subtract the specified amount of time from the given calendar field according to the rules of the calendar
    public final void set(int year,int month,int date)Set the month, year and day of the current calendar
  • Sample code

    public class CalendarDemo {
        public static void main(String[] args) {
            //Get calendar class object
            Calendar c = Calendar.getInstance();
    
            //public int get(int field): returns the value of the given calendar field
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH) + 1;
            int date = c.get(Calendar.DATE);
            System.out.println(year + "year" + month + "month" + date + "day");
    
            //public abstract void add(int field, int amount): adds or subtracts a given calendar field from a specified amount of time according to calendar rules
            //Demand 1: today 3 years ago
    //        c.add(Calendar.YEAR,-3);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + "year" + month + "month" + date + "day");
    
            //Demand 2: 10 days after 10 years
    //        c.add(Calendar.YEAR,10);
    //        c.add(Calendar.DATE,-10);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + "year" + month + "month" + date + "day");
    
            //public final void set(int year,int month,int date): sets the month, year and day of the current calendar
            c.set(2050,10,10);
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH) + 1;
            date = c.get(Calendar.DATE);
            System.out.println(year + "year" + month + "month" + date + "day");
    
        }
    }
    

2.6 February day case (application)

  • Case requirements

    Get the number of days in February of any year

  • code implementation

    public class CalendarTest {
        public static void main(String[] args) {
            //Enter any year on the keyboard
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter year:");
            int year = sc.nextInt();
    
            //Set year, month and day of calendar object
            Calendar c = Calendar.getInstance();
            c.set(year, 2, 1);
    
            //March 1 is pushed forward one day, which is the last day of February
            c.add(Calendar.DATE, -1);
    
            //Just get the output of this day
            int date = c.get(Calendar.DATE);
            System.out.println(year + "In February" + date + "day");
        }
    }
    

3. Abnormal

3.1 abnormality (memory)

  • Overview of exceptions

    An exception is an abnormal condition in the program

  • Abnormal architecture

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RZJoP2H7-1627043568470)(img(.png)]

3.2 the JVM handles exceptions by default (understanding)

  • If there is a problem with the program, we do not do any processing. Finally, the JVM will do the default processing. The processing method includes the following two steps:

  • The name of the exception, the cause of the error and the location of the exception are output to the console

  • Program stop

3.3try catch exception handling (application)

  • Define format

    try {
    	Possible exception codes;
    } catch(Exception class name variable name) {
    	Exception handling code;
    }
    
  • Execution process

    • The program starts from the code in try
    • If an exception occurs, it will jump to the corresponding catch for execution
    • After execution, the program can continue to execute
  • Sample code

    public class ExceptionDemo01 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("end");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]);
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) {
    //            System.out.println("the array index you accessed does not exist, please go back and modify it to the correct index");
                e.printStackTrace();
            }
        }
    }
    

3.4 throwable member method (application)

  • common method

    Method nameexplain
    public String getMessage()Returns the detailed message string for this throwable
    public String toString()Returns a short description of this throw
    public void printStackTrace()Output the abnormal error message to the console
  • Sample code

    public class ExceptionDemo02 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("end");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
    //            e.printStackTrace();
    
                //public String getMessage(): returns the detailed message string of this throwable
    //            System.out.println(e.getMessage());
                //Index 3 out of bounds for length 3
    
                //public String toString(): returns a short description of this throw
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace(): output the abnormal error information on the console
                e.printStackTrace();
    //            java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    //            at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
    //            at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
    
            }
        }
    }
    

3.5 difference between compile time exception and run-time exception (memory)

  • Compile time exception

    • Are all Exception classes and their subclasses
    • The processing must be displayed, otherwise the program will have an error and cannot be compiled
  • Runtime exception

    • Are RuntimeException class and its subclasses
    • You do not need to display the handling, but you can also handle the exception as you do at compile time

3.6 handling exceptions in throws mode (application)

  • Define format

    public void method() throws Exception class name {
        
    }
    
  • Sample code

    public class ExceptionDemo {
        public static void main(String[] args) {
            System.out.println("start");
    //        method();
            try {
                method2();
            }catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("end");
        }
    
        //Compile time exception
        public static void method2() throws ParseException {
            String s = "2048-08-09";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse(s);
            System.out.println(d);
        }
    
        //Runtime exception
        public static void method() throws ArrayIndexOutOfBoundsException {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
        }
    }
    
  • matters needing attention

    • The throws format follows the parentheses of the method
    • Exceptions must be handled during compilation. There are two processing schemes: try... catch... Or throws. If the throw scheme is adopted, who will call who to handle them in the future
    • Runtime exceptions can not be handled. After a problem occurs, we need to come back and modify the code

3.7 difference between throws and throw (memory)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GnrF2NS8-1627043568472)(img].png)]

3.8 custom exception (application)

  • Custom exception class

    public class ScoreException extends Exception {
    
        public ScoreException() {}
    
        public ScoreException(String message) {
            super(message);
        }
    
    }
    
  • Teacher class

    public class Teacher {
        public void checkScore(int score) throws ScoreException {
            if(score<0 || score>100) {
    //            throw new ScoreException();
                throw new ScoreException("The score you gave is wrong. The score should be 0-100 between");
            } else {
                System.out.println("Normal performance");
            }
        }
    }
    
  • Test class

    public class Demo {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter a score:");
    
            int score = sc.nextInt();
    
            Teacher t = new Teacher();
            try {
                t.checkScore(score);
            } catch (ScoreException e) {
                e.printStackTrace();
            }
        }
    }
    

1.Collection collection

1.1 collective Architecture [memory]

  • Characteristics of set classes

    A storage model with variable storage space is provided, and the stored data capacity can be changed at any time

  • System diagram of collection class

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Z2ruqMRU-1627106583760)(img(.png)]

1.2Collection set overview and basic usage [ application ]

  • Collection collection overview

    • Is the top-level interface of a singleton Collection. It represents a set of objects, which are also called Collection elements

    • JDK does not provide any direct implementation of this interface. It provides more specific implementation of sub interfaces (such as Set and List)

  • Collection basic usage

    public class CollectionDemo01 {
        public static void main(String[] args) {
            //Create an object for the Collection
            Collection<String> c = new ArrayList<String>();
    
            //Add element: Boolean add (E)
            c.add("hello");
            c.add("world");
            c.add("java");
    
            //Output collection object
            System.out.println(c);
        }
    }
    

1.3 common methods of collection [application]

Method nameexplain
boolean add(E e)Add element
boolean remove(Object o)Removes the specified element from the collection
void clear()Empty elements in collection
boolean contains(Object o)Determines whether the specified element exists in the collection
boolean isEmpty()Determine whether the collection is empty
int size()The length of the set, that is, the number of elements in the set

1.4 traversal of collection [application]

  • Introduction to iterators
    • Iterator, special traversal mode of collection
    • Iterator iterator(): returns the iterator of the elements in this collection, which is obtained through the iterator() method of the collection
    • The iterator is obtained through the iterator() method of the collection, so we say that it depends on the collection
  • Traversal of Collection
public class IteratorDemo {
    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<>();

        //Add element
        c.add("hello");
        c.add("world");
        c.add("java");
        c.add("javaee");

        //Iterator < E > iterator(): returns the iterator of the elements in this collection, which is obtained through the iterator() method of the collection
        Iterator<String> it = c.iterator();

        //Using while loop to improve the judgment and acquisition of elements
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
 
        

1.5 illustration of collective use steps [understanding]

  • Use steps

[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yCSNP1ak-1627106583761)(img].png)]

1.6 case of Collection - the Collection stores student objects and traverses [application]

  • Case requirements

    Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

  • code implementation

    • Student class
    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
    • Test class
    public class CollectionDemo {
        public static void main(String[] args) {
            //Collection object creation collection
            Collection<Student> c = new ArrayList<Student>();
    
            //Create student object
            Student s1 = new Student("Lin Qingxia", 30);
            Student s2 = new Student("Zhang Manyu", 35);
            Student s3 = new Student("Wang Zuxian", 33);
    
            //Add students to collection
            c.add(s1);
            c.add(s2);
            c.add(s3);
    
            //Traversal collection (iterator mode)
            Iterator<Student> it = c.iterator();
            while (it.hasNext()) {
                Student s = it.next();
                System.out.println(s.getName() + "," + s.getAge());
            }
        }
    }
    

2.List set

2.1 list set overview and features [memory]

  • List collection overview
    • An ordered set (also known as a sequence), in which the user can accurately control the insertion position of each element in the list. Users can access elements through integer indexes and search for elements in the list
    • Unlike Set collections, lists usually allow duplicate elements
  • List set features
    • Indexed
    • Duplicate elements can be stored
    • Element access order

2.2 unique method of list set [application]

Method namedescribe
void add(int index,E element)Inserts the specified element at the specified location in this collection
E remove(int index)Deletes the element at the specified index and returns the deleted element
E set(int index,E element)Modify the element at the specified index and return the modified element
E get(int index)Returns the element at the specified index

2.3 case of the set - the List set stores the student object and traverses the [application]

  • Case requirements

    Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

  • code implementation

    • Student class

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • Test class

      public class ListDemo {
          public static void main(String[] args) {
              //Create a List collection object
              List<Student> list = new ArrayList<Student>();
      
              //Create student object
              Student s1 = new Student("Lin Qingxia", 30);
              Student s2 = new Student("Zhang Manyu", 35);
              Student s3 = new Student("Wang Zuxian", 33);
      
              //Add students to collection
              list.add(s1);
              list.add(s2);
              list.add(s3);
      
              //Iterator pattern 
              Iterator<Student> it = list.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName() + "," + s.getAge());
              }
              
              System.out.println("--------");
      
              //for loop mode
              for(int i=0; i<list.size(); i++) {
                  Student s = list.get(i);
                  System.out.println(s.getName() + "," + s.getAge());
              }
      
          }
      }
      

2.4 concurrent modification exception [ application ]

  • Causes of occurrence

    In the process of iterator traversal, the elements in the collection are modified through the collection object, resulting in the inconsistency between the expected modified value and the actual modified value in the element obtained by the iterator: ConcurrentModificationException

  • Solutions

    Use the for loop to traverse, and then use the collection object to do the corresponding operation

  • Sample code

    public class ListDemo {
        public static void main(String[] args) {
            //Create collection object
            List<String> list = new ArrayList<String>();
    
            //Add element
            list.add("hello");
            list.add("world");
            list.add("java");
    
            //Traverse the collection to get each element. See if there is a "world" element. If so, I will add a "javaee" element. Please write code to implement it
    //        Iterator<String> it = list.iterator();
    //        while (it.hasNext()) {
    //            String s = it.next();
    //            if(s.equals("world")) {
    //                list.add("javaee");
    //            }
    //        }
    
            for(int i=0; i<list.size(); i++) {
                String s = list.get(i);
                if(s.equals("world")) {
                    list.add("javaee");
                }
            }
    
            //Output collection object
            System.out.println(list);
        }
    }
    

2.5 list iterator [application]

  • Introduction to ListIterator

    • It is obtained through the listIterator() method of the List collection, so it is a unique iterator of the List collection
    • A list iterator that allows the programmer to traverse in either direction, modify the list during the iteration, and get the current position of the iterator in the list
  • Sample code

    public class ListIteratorDemo {
        public static void main(String[] args) {
            //Create collection object
            List<String> list = new ArrayList<String>();
    
            //Add element
            list.add("hello");
            list.add("world");
            list.add("java");
    
            //Get list iterator
            ListIterator<String> lit = list.listIterator();
            while (lit.hasNext()) {
                String s = lit.next();
                if(s.equals("world")) {
                    lit.add("javaee");
                }
            }
    
            System.out.println(list);
    
        }
    }
    

2.6 enhanced for loop [application]

  • Define format

    for(Element data type variable name : array/Collection object name) {
        Circulatory body;
    }
    
  • Sample code

    public class ForDemo {
        public static void main(String[] args) {
            int[] arr = {1,2,3,4,5};
            for(int i : arr) {
                System.out.println(i);
            }
            
            System.out.println("--------");
    
            String[] strArray = {"hello","world","java"};
            for(String s : strArray) {
                System.out.println(s);
            }
            
            System.out.println("--------");
    
            List<String> list = new ArrayList<String>();
            list.add("hello");
            list.add("world");
            list.add("java");
    
            for(String s : list) {
                System.out.println(s);
            }
            
            System.out.println("--------");
    
            //The internal principle is an Iterator iterator
            /*
            for(String s : list) {
                if(s.equals("world")) {
                    list.add("javaee"); //ConcurrentModificationException
                }
            }
            */
        }
    }
    

2.7 set case List set stores student objects and traverses [application] in three ways

  • Case requirements

    Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

  • code implementation

    • Student class

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • Test class

      public class ListDemo {
          public static void main(String[] args) {
              //Create a List collection object
              List<Student> list = new ArrayList<Student>();
      
              //Create student object
              Student s1 = new Student("Lin Qingxia", 30);
              Student s2 = new Student("Zhang Manyu", 35);
              Student s3 = new Student("Wang Zuxian", 33);
      
              //Add students to collection
              list.add(s1);
              list.add(s2);
              list.add(s3);
      
              //Iterators: Collection specific traversal
              Iterator<Student> it = list.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName()+","+s.getAge());
              }
              System.out.println("--------");
      
              //Normal for: traversal with index
              for(int i=0; i<list.size(); i++) {
                  Student s = list.get(i);
                  System.out.println(s.getName()+","+s.getAge());
              }
              System.out.println("--------");
      
              //Enhanced for: the most convenient traversal method
              for(Student s : list) {
                  System.out.println(s.getName()+","+s.getAge());
              }
          }
      }
      

3. Data structure

3.1 stack and queue of data structure [memory]

  • Stack structure

    In and out

  • Queue structure

    First in first out

3.2 array and linked list of data structure [memory]

  • Array structure

    Fast query, slow addition and deletion

  • Queue structure

    Slow query, fast addition and deletion

4. Implementation class of list set

4.1 characteristics of list aggregation subclass [memory]

  • ArrayList collection

    The bottom layer is the implementation of array structure, with fast query and slow addition and deletion

  • LinkedList collection

    The bottom layer is the implementation of linked list structure, with slow query and fast addition and deletion

4.2 case of the collection - the ArrayList collection stores student objects and traverses [application] in three ways

  • Case requirements

    Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

  • code implementation

    • Student class

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • Test class

      public class ArrayListDemo {
          public static void main(String[] args) {
              //Create an ArrayList collection object
              ArrayList<Student> array = new ArrayList<Student>();
      
              //Create student object
              Student s1 = new Student("Lin Qingxia", 30);
              Student s2 = new Student("Zhang Manyu", 35);
              Student s3 = new Student("Wang Zuxian", 33);
      
              //Add students to collection
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //Iterators: Collection specific traversal
              Iterator<Student> it = array.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName() + "," + s.getAge());
              }
              System.out.println("--------");
      
              //Normal for: traversal with index
              for(int i=0; i<array.size(); i++) {
                  Student s = array.get(i);
                  System.out.println(s.getName() + "," + s.getAge());
              }
              System.out.println("--------");
      
              //Enhanced for: the most convenient traversal method
              for(Student s : array) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

4.3 unique function of LinkedList set [application]

  • Unique method

    Method nameexplain
    public void addFirst(E e)Inserts the specified element at the beginning of the list
    public void addLast(E e)Appends the specified element to the end of this list
    public E getFirst()Returns the first element in this list
    public E getLast()Returns the last element in this list
    public E removeFirst()Removes and returns the first element from this list
    public E removeLast()Removes and returns the last element from this list

1.Set set

1.1 set overview and features [application]

  • Characteristics of Set
    • Element access disorder
    • No index, traversal only through iterators or enhanced for loops
    • Duplicate elements cannot be stored
  • Basic use of Set
public class SetDemo {
    public static void main(String[] args) {
        //Create collection object
        Set<String> set = new HashSet<String>();

        //Add element
        set.add("hello");
        set.add("world");
        set.add("java");
        //A collection that does not contain duplicate elements
        set.add("world");

        //ergodic
        for(String s : set) {
            System.out.println(s);
        }
    }
}

1.2 hash value [understanding]

  • Introduction to hash values

    It is a numeric value of type int calculated by JDK according to the address or string or number of the object

  • How to get hash value

    public int hashCode() in Object class: returns the hash code value of the Object

  • Characteristics of hash value

    • The hashCode() method is called multiple times for the same object, and the returned hash value is the same
    • By default, different objects have different hash values. Rewriting the hashCode() method can make the hash values of different objects the same
  • The code that gets the hash value

    • Student class
    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public int hashCode() {
            return 0;
        }
    }
    
    • Test class
    public class HashDemo {
        public static void main(String[] args) {
            //Create student object
            Student s1 = new Student("Lin Qingxia",30);
    
            //The hashCode() method is called multiple times for the same object, and the returned hash value is the same
            System.out.println(s1.hashCode()); //1060830840
            System.out.println(s1.hashCode()); //1060830840
            System.out.println("--------");
    
            Student s2 = new Student("Lin Qingxia",30);
    
            //By default, different objects have different hash values
            //Through method rewriting, you can realize that the hash values of different objects are the same
            System.out.println(s2.hashCode()); //2137211482
            System.out.println("--------");
    
            System.out.println("hello".hashCode()); //99162322
            System.out.println("world".hashCode()); //113318802
            System.out.println("java".hashCode()); //3254818
    
            System.out.println("world".hashCode()); //113318802
            System.out.println("--------");
    
            System.out.println("Heavily".hashCode()); //1179395
            System.out.println("conversation".hashCode()); //1179395
        }
    }
    

1.3 HashSet set overview and features [application]

  • Characteristics of HashSet set

    • The underlying data structure is a hash table
    • The iterative order of the set is not guaranteed, that is, the order of stored and extracted elements is not guaranteed
    • There is no indexed method, so you can't use a normal for loop to traverse
    • Because it is a Set set, it is a Set that does not contain duplicate elements
  • Basic use of HashSet sets

    public class HashSetDemo01 {
        public static void main(String[] args) {
            //Create collection object
            HashSet<String> hs = new HashSet<String>();
    
            //Add element
            hs.add("hello");
            hs.add("world");
            hs.add("java");
    
            hs.add("world");
    
            //ergodic
            for(String s : hs) {
                System.out.println(s);
            }
        }
    }
    

1.4 analysis of source code for ensuring element uniqueness of HashSet set [understanding]

  • The principle of ensuring element uniqueness in HashSet set

    ​ 1. Calculates the storage location based on the hash value of the object

    If there is no element in the current position, it is stored directly

    If an element exists in the current position, go to step 2

    ​ 2. Compare the hash value between the element of the current element and the existing element

    If the hash values are different, the current element is stored

    If the hash values are the same, proceed to step 3

    ​ 3. Compare the contents of the two elements through the equals() method

    If the contents are different, the current element is stored

    If the contents are the same, the current element is not stored

  • HashSet sets are diagrams that guarantee the uniqueness of elements

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tPdgxc3G-1627113989601)(img(.png)]

1.5 hash table of common data structures [understanding]

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jr5T0B92-1627113989604)(img].png)]

1.6 the HashSet set stores the student object and traverses the application

  • Case requirements

    • Create a collection to store student objects, store multiple student objects, and use the program to traverse the collection on the console
    • Requirement: if the member variable values of the student object are the same, we think it is the same object
  • code implementation

    • Student class

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
      
              Student student = (Student) o;
      
              if (age != student.age) return false;
              return name != null ? name.equals(student.name) : student.name == null;
          }
      
          @Override
          public int hashCode() {
              int result = name != null ? name.hashCode() : 0;
              result = 31 * result + age;
              return result;
          }
      }
      
    • Test class

      public class HashSetDemo02 {
          public static void main(String[] args) {
              //Create a HashSet collection object
              HashSet<Student> hs = new HashSet<Student>();
      
              //Create student object
              Student s1 = new Student("Lin Qingxia", 30);
              Student s2 = new Student("Zhang Manyu", 35);
              Student s3 = new Student("Wang Zuxian", 33);
      
              Student s4 = new Student("Wang Zuxian", 33);
      
              //Add students to collection
              hs.add(s1);
              hs.add(s2);
              hs.add(s3);
              hs.add(s4);
      
              //Traversal collection (enhanced for)
              for (Student s : hs) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

1.7 linkedhashset set overview and features [application]

  • LinkedHashSet set features

    • The implementation of hash table and Set predictable linked list
    • The order of elements is guaranteed by the linked list, that is, the storage and extraction order of elements are consistent
    • The hash table ensures that the elements are unique, that is, there are no duplicate elements
  • LinkedHashSet set basic usage

    public class LinkedHashSetDemo {
        public static void main(String[] args) {
            //Create collection object
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
    
            //Add element
            linkedHashSet.add("hello");
            linkedHashSet.add("world");
            linkedHashSet.add("java");
    
            linkedHashSet.add("world");
    
            //Traversal set
            for(String s : linkedHashSet) {
                System.out.println(s);
            }
        }
    }
    

2.Set sorting

2.1 overview and characteristics of TreeSet set [application]

  • TreeSet collection overview

    • Elements are ordered and can be sorted according to certain rules. The specific sorting method depends on the construction method
      • TreeSet(): sort according to the natural order of its elements
      • TreeSet (comparator): sort according to the specified comparator
    • There is no indexed method, so you can't use a normal for loop to traverse
    • A collection that does not contain duplicate elements because it is a Set collection
  • TreeSet collection basic usage

    public class TreeSetDemo01 {
        public static void main(String[] args) {
            //Create collection object
            TreeSet<Integer> ts = new TreeSet<Integer>();
    
            //Add element
            ts.add(10);
            ts.add(40);
            ts.add(30);
            ts.add(50);
            ts.add(20);
    
            ts.add(30);
    
            //Traversal set
            for(Integer i : ts) {
                System.out.println(i);
            }
        }
    }
    

2.2 use of natural sorting Comparable [application]

  • Case requirements

    • Store and traverse the student object, create a TreeSet collection, and use the parameterless construction method
    • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name
  • Implementation steps

    • The TreeSet collection is used to store custom objects. The parameterless construction method uses natural sorting to sort elements
    • Natural sorting is to let the class to which the element belongs implement the Comparable interface and override the compareTo(T o) method
    • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions
  • code implementation

    • Student class

      public class Student implements Comparable<Student> {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public int compareTo(Student s) {
      //        return 0;
      //        return 1;
      //        return -1;
              //Sorted by age
             int num = this.age - s.age;
      //        int num = s.age - this.age;
              //When the age is the same, sort alphabetically by name
             int num2 = num==0?this.name.compareTo(s.name):num;
              return num2;
          }
      }
      
    • Test class

      public class TreeSetDemo02 {
          public static void main(String[] args) {
              //Create collection object
              TreeSet<Student> ts = new TreeSet<Student>();
      
              //Create student object
              Student s1 = new Student("xishi", 29);
              Student s2 = new Student("wangzhaojun", 28);
              Student s3 = new Student("diaochan", 30);
              Student s4 = new Student("yangyuhuan", 33);
      
              Student s5 = new Student("linqingxia",33);
              Student s6 = new Student("linqingxia",33);
      
              //Add students to collection
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
      
              //Traversal set
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

2.3 use of Comparator sorting Comparator [ application ]

  • Case requirements

    • Store the student object and traverse it, create a TreeSet collection, and use the construction method with parameters
    • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name
  • Implementation steps

    • The user-defined objects are stored in the TreeSet collection. The construction method with parameters uses comparator sorting to sort the elements
    • Comparator sorting is to let the collection construction method receive the implementation class object of comparator and rewrite the compare(T o1,T o2) method
    • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions
  • code implementation

    • Student class

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • Test class

      public class TreeSetDemo {
          public static void main(String[] args) {
              //Create collection object
              TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
                      //this.age - s.age
                      //s1,s2
                      int num = s1.getAge() - s2.getAge();
                      int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                      return num2;
                  }
              });
      
              //Create student object
              Student s1 = new Student("xishi", 29);
              Student s2 = new Student("wangzhaojun", 28);
              Student s3 = new Student("diaochan", 30);
              Student s4 = new Student("yangyuhuan", 33);
      
              Student s5 = new Student("linqingxia",33);
              Student s6 = new Student("linqingxia",33);
      
              //Add students to collection
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
      
              //Traversal set
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

2.4 case of ranking scores [ application ]

  • Case requirements

    • Use TreeSet set to store multiple student information (name, Chinese score, mathematics score), and traverse the set
    • Requirements: appear from high to low according to the total score
  • code implementation

    • Student class

      public class Student {
          private String name;
          private int chinese;
          private int math;
      
          public Student() {
          }
      
          public Student(String name, int chinese, int math) {
              this.name = name;
              this.chinese = chinese;
              this.math = math;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getChinese() {
              return chinese;
          }
      
          public void setChinese(int chinese) {
              this.chinese = chinese;
          }
      
          public int getMath() {
              return math;
          }
      
          public void setMath(int math) {
              this.math = math;
          }
      
          public int getSum() {
              return this.chinese + this.math;
          }
      }
      
    • Test class

      public class TreeSetDemo {
          public static void main(String[] args) {
              //Create a TreeSet collection object and sort by comparator sorting
              TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
      //                int num = (s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
                      //Main conditions
                      int num = s2.getSum() - s1.getSum();
                      //minor criteria 
                      int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                      int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                      return num3;
                  }
              });
      
              //Create student object
              Student s1 = new Student("Lin Qingxia", 98, 100);
              Student s2 = new Student("Zhang Manyu", 95, 95);
              Student s3 = new Student("Wang Zuxian", 100, 93);
              Student s4 = new Student("Liuyan", 100, 97);
              Student s5 = new Student("Breezy", 98, 98);
      
              Student s6 = new Student("Zuo lengchan", 97, 99);
      //        Student s7 = new Student("left cold Zen", 97, 99);
              Student s7 = new Student("Zhao Yun", 97, 99);
      
              //Add student object to collection
              ts.add(s1);
              ts.add(s2);
              ts.add(s3);
              ts.add(s4);
              ts.add(s5);
              ts.add(s6);
              ts.add(s7);
      
              //Traversal set
              for (Student s : ts) {
                  System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath() + "," + s.getSum());
              }
          }
      }
      

2.5 non repeated random number cases [application]

  • Case requirements

    • Write a program to obtain 10 random numbers between 1-20. It is required that the random numbers cannot be repeated and output on the console
  • code implementation

    public class SetDemo {
        public static void main(String[] args) {
            //Create Set collection object
    //        Set<Integer> set = new HashSet<Integer>();
            Set<Integer> set = new TreeSet<Integer>();
    
            //Create random number object
            Random r = new Random();
    
            //Judge whether the length of the set is less than 10
            while (set.size()<10) {
                //Generate a random number and add it to the collection
                int number = r.nextInt(20) + 1;
                set.add(number);
            }
    
            //Traversal set
            for(Integer i : set) {
                System.out.println(i);
            }
        }
    }
    

3. Generics

3.1 generic overview and benefits [understanding]

  • Generic overview

    Is a feature introduced in JDK5. It provides a compile time type safety detection mechanism, which allows illegal types to be detected at compile time

    Its essence is parameterized type, that is, the data type operated is specified as a parameter. When referring to parameters, the most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the method is called. So what about parameterized types? As the name suggests, it is to parameterize the type from the original specific type, and then pass in the specific type when using / calling. This parameter type can be used in classes, methods and interfaces, which are called generic classes, generic methods and generic interfaces respectively

  • Generic definition format

    • < type >: Specifies the format of a type. The type here can be regarded as a formal parameter
    • < type 1, type 2... >: specify mu lt iple types of formats separated by commas. The type here can be regarded as a formal parameter
    • In the future, the given type can be regarded as an argument, and the type of the argument can only be a reference data type
  • Benefits of generics

    • Advance the run-time problem to compile time
    • Casts are avoided

3.2 generic class [application]

  • Define format

    Modifier  class Class name<type> {  }
    
  • Sample code

    • Generic class

      public class Generic<T> {
          private T t;
      
          public T getT() {
              return t;
          }
      
          public void setT(T t) {
              this.t = t;
          }
      }
      
    • Test class

      public class GenericDemo {
          public static void main(String[] args) {
              Generic<String> g1 = new Generic<String>();
              g1.setT("Lin Qingxia");
              System.out.println(g1.getT());
      
              Generic<Integer> g2 = new Generic<Integer>();
              g2.setT(30);
              System.out.println(g2.getT());
      
              Generic<Boolean> g3 = new Generic<Boolean>();
              g3.setT(true);
              System.out.println(g3.getT());
          }
      }
      

3.3 generic method [application]

  • Define format

    Modifier  <type> Return value type method name(Type variable name) {  }
    
  • Sample code

    • Classes with generic methods

      public class Generic {
          public <T> void show(T t) {
              System.out.println(t);
          }
      }
      
    • Test class

      public class GenericDemo {
          public static void main(String[] args) {
      		Generic g = new Generic();
              g.show("Lin Qingxia");
              g.show(30);
              g.show(true);
              g.show(12.34);
          }
      }
      

3.4 generic interface [ application ]

  • Define format

    Modifier  interface Interface name<type> {  }
    
  • Sample code

    • generic interface

      public interface Generic<T> {
          void show(T t);
      }
      
    • Generic interface implementation class

      public class GenericImpl<T> implements Generic<T> {
          @Override
          public void show(T t) {
              System.out.println(t);
          }
      }
      
    • Test class

      public class GenericDemo {
          public static void main(String[] args) {
              Generic<String> g1 = new GenericImpl<String>();
              g1.show("Lin Qingxia");
      
              Generic<Integer> g2 = new GenericImpl<Integer>();
              g2.show(30);
          }
      }
      

3.5 type wildcard [application]

  • Role of type wildcards

    To represent the parent classes of various generic lists, you can use type wildcards

  • Classification of type wildcards

    • Type wildcard: <? >
      • List<?>: Represents a list whose element type is unknown, and its elements can match any type
      • This List with wildcards only indicates that it is the parent of various generic lists, and cannot add elements to it
    • Upper limit of type wildcard: <? Extensions type >
      • List<? Extensions Number >: the type it represents is Number or its subtype
    • Type wildcard lower limit: <? Super type >
      • List<? Super Number >: the type it represents is Number or its parent type
  • Basic use of type wildcards

    public class GenericDemo {
        public static void main(String[] args) {
            //Type wildcard: <? >
            List<?> list1 = new ArrayList<Object>();
            List<?> list2 = new ArrayList<Number>();
            List<?> list3 = new ArrayList<Integer>();
            System.out.println("--------");
    
            //Upper limit of type wildcard: <? Extensions type >
    //        List<? extends Number> list4 = new ArrayList<Object>();
            List<? extends Number> list5 = new ArrayList<Number>();
            List<? extends Number> list6 = new ArrayList<Integer>();
            System.out.println("--------");
    
            //Type wildcard lower limit: <? Super type >
            List<? super Number> list7 = new ArrayList<Object>();
            List<? super Number> list8 = new ArrayList<Number>();
    //        List<? super Number> list9 = new ArrayList<Integer>();
    
        }
    }
    

4. Variable parameters

4.1 variable parameters [ application ]

  • Introduction to variable parameters

    Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable

  • Variable parameter definition format

    Modifier return value type method name(Data type... Variable name) {  }
    
  • Precautions for variable parameters

    • The variable here is actually an array
    • If a method has multiple parameters, including variable parameters, the variable parameters should be placed last
  • Basic use of variable parameters

    public class ArgsDemo01 {
        public static void main(String[] args) {
            System.out.println(sum(10, 20));
            System.out.println(sum(10, 20, 30));
            System.out.println(sum(10, 20, 30, 40));
    
            System.out.println(sum(10,20,30,40,50));
            System.out.println(sum(10,20,30,40,50,60));
            System.out.println(sum(10,20,30,40,50,60,70));
            System.out.println(sum(10,20,30,40,50,60,70,80,90,100));
        }
    
    //    public static int sum(int b,int... a) {
    //        return 0;
    //    }
    
        public static int sum(int... a) {
            int sum = 0;
            for(int i : a) {
                sum += i;
            }
            return sum;
        }
    }
    

4.2 use of variable parameters [ application ]

  • There is a static method in the Arrays tool class:

    • public static List asList(T... a): returns a fixed size list supported by the specified array
    • The returned collection cannot be added or deleted, but can be modified
  • There is a static method in the List interface:

    • public static List of(E... elements): returns an immutable list containing any number of elements
    • The returned collection cannot be added, deleted or modified
  • There is a static method in the Set interface:

    • public static Set of(E... elements): returns an immutable set containing any number of elements
    • When giving elements, you cannot give duplicate elements
    • The returned collection cannot be added or deleted. There is no modified method
  • Sample code

    public class ArgsDemo02 {
        public static void main(String[] args) {
            //Public static < T > List < T > aslist (t... A): returns a fixed size list supported by the specified array
    //        List<String> list = Arrays.asList("hello", "world", "java");
    //
            list.add("javaee"); //UnsupportedOperationException
            list.remove("world"); //UnsupportedOperationException
    //        list.set(1,"javaee");
    //
    //        System.out.println(list);
    
            //Public static < E > List < E > of (E... Elements): returns an immutable list containing any number of elements
    //        List<String> list = List.of("hello", "world", "java", "world");
    //
            list.add("javaee");//UnsupportedOperationException
            list.remove("java");//UnsupportedOperationException
            list.set(1,"javaee");//UnsupportedOperationException
    //
    //        System.out.println(list);
    
            //Public static < E > set < E > of (E... Elements): returns an immutable set containing any number of elements
    //        Set<String> set = Set.of("hello", "world", "java","world"); //IllegalArgumentException
            //Set<String> set = Set.of("hello", "world", "java");
    
    //        set.add("javaee");//UnsupportedOperationException
    //        set.remove("world");//UnsupportedOperationException
    
            //System.out.println(set);
        }
    }
    

Keywords: Java

Added by trassalg on Fri, 14 Jan 2022 22:25:09 +0200