Java Basic Review (9)
generic paradigm
Definition:
Receiving a data type by <Data Type> detects elements in a collection using this data type at compilation time. If the element is not of the type specified in <>, it is not allowed to be added to the current collection (compilation failure).
Effect:
- The use of generics eliminates the need for fault-tolerant processing, downward transformation, forced type conversion - simplifying code
- The problems in the run-time are checked in the compile-time ahead of time, which improves the security of the code and the efficiency of programming.
Generics can modify classes, methods, interfaces.
1. Generic applications on classes
Add generics to the Student class by adding directly after the class. E stands for any data type. Note that this is not necessarily E, any letter can be used.
-
This is using generics on classes.
-
Generics identified on classes can be used directly in methods
-
Object by default when generics are not specified
-
When the generic type is determined, the type is determined.
Student<Phone> student1 = new Student<>(); class Student<E>{ E tools; public E getTools() { return tools; } public void setTools(E tools) { this.tools = tools; } }
2. Application of generics in methods
-
Generics can be used to define more than one at a time.
-
Method generics are consistent with class generics
class Dog<F>{ public void eat(F f) { System.out.println(f); } }
-
Methodologically independent use of generics
-
Note: Generics must be defined before they are used
-
Definition: Add < generic > to the front of the current method
-
Function: Keep methods and generics consistent
public <E> void song(E e) { ArrayList<E> arrayList = new ArrayList<>(); System.out.println(e); }
-
-
Use generics on static methods
-
Must be used independently
-
Way: Define generic < generic > after static
public static <W> void show(W w) { }
-
-
Example
package Collection; import java.util.ArrayList; public class demo8 { public static void main(String[] args) { Dog<String> dog = new Dog<>(); dog.eat("eat"); dog.song("Wang Wang"); } } class Dog<E>{ public void eat(E e){ System.out.println(e); } public <F> void song(F f){ ArrayList<F> arrayList = new ArrayList<>(); System.out.println(f); } public static <W> void show(W w) { } }
3. Generic applications on interfaces
The main research is how to use generics on subclasses of interfaces.
-
Generics on subclasses are consistent with interfaces
- Generics on classes are determined, generics on interfaces are determined, and generics on methods are determined.
-
Use generics on interfaces and no generics on subclasses
- A specific generic type must be specified at the interface location of the implementation
-
Methods In the case of generics:
- If the method is overridden, generics are consistent with interfaces
- If the subclass has its own method, it can be consistent with the interface, or it can have its own generics.
-
Example
package com.qf.test; /* * Generic applications on interfaces * Our main research is how generics on subclasses of interfaces are used. */ public class Demo13 { public static void main(String[] args) { //1. Generics on subclasses are consistent with interfaces Pig<String> pig = new Pig<>(); pig.show("Ha-ha"); //2. Use generics on interfaces and no generics on subclasses Bird bird = new Bird(); bird.show("haha"); Class<?> class1 = bird.getClass(); } } interface Inte<E>{ public void show(E e); } //1. Generics on subclasses are consistent with interfaces /* Generics on classes are determined, generics on interfaces are determined, and generics on methods are determined. */ class Pig<E> implements Inte<E>{ @Override public void show(E e) { System.out.println(e); } } //2. Use generics on interfaces and no generics on subclasses /*A specific generic type must be specified at the interface location of the implementation * * Methods In the case of generics: * 1.If the method is overridden, generics are consistent with interfaces * 2.If the subclass has its own method, it can be consistent with the interface, or it can have its own generics. */ class Bird implements Inte<String>{ public void show(String e) {}; }
About Java? Use
1) Used for?: Here is part of the Operator Operator, which is preceded by the Judgment Conditions and followed by the results of two branches.
2) The sql statement select * from EMP where name=?: Represents a placeholder
3) Used for generics to represent any data type.
//Object here has nothing to do with the previous one? Class<?> class1 = Object.class; //If the generic type of a class is written as? Yes. As a return value, it defaults to Object type, but not as a parameter. So when specifying a generic type for an object, it is necessary to write a specific type. Test<?> test = new Test(); //test.run(new Object()); class Test<T>{ T e; public T run(T a) { T t = null; return t; } }
? Wildcards
Can represent one or more data types
-
Limitation upper limit: <? Extends E> Limits the whole <> preferable generic type upper limit is E,<> preferable types are subclasses of E and E.
public class Demo14 { public static void main(String[] args) { // ArrayList<Student2> list1 = new ArrayList<>(); list1.add(new Student2("bingbing", 1)); //Reference can be passed: Because Student2 is a subclass of Person1, traversal can be achieved. bianli(list1); ArrayList<Teacher> list2 = new ArrayList<>(); list2.add(new Teacher("bingbing", 1)); //Reference can be passed: Teacher1 is a subclass of Person1, which enables traversal bianli(list2); ArrayList<Person4> list3 = new ArrayList<>(); list3.add(new Person4("bingbing", 1)); //It can be transmitted for reference. bianli(list3); ArrayList<Object> list4 = new ArrayList<>(); list4.add(new Object()); //No parameterization: Because Object is the parent of Person1, traversal is not possible //bianli(list4); } public static void bianli(Collection<? extends Person4> e){ System.out.println("Traversed"); } } class Person4{ String name; int age; public Person4() { super(); // TODO Auto-generated constructor stub } public Person4(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person4 [name=" + name + ", age=" + age + "]"; } } class Teacher extends Person4{ public Teacher(String name, int age) { super(name, age); } } class Student2 extends Person4 { public Student2(String name, int age) { super(name, age); } }
-
Limit Lower Limit: <? Super E> Limits the whole <> acceptable generic type lower limit is E, and the preferable type in <> is the parent class of E and E.
Variable parameters
The number of parameters can be changed to simplify the code and operation.
CHARACTERISTICS OF VARIABLE PARAMETERS
-
Parameters that pass values to variable parameters can be written directly. There is no limit to the number of parameters, and they are automatically put into variable arrays.
-
When there are multiple parameters including variable parameters, variable parameters must be placed at the end, and at most one variable parameter can be used in a method.
-
When the method with variable parameters is overloaded with the method with fixed parameters, the order of invocation takes precedence over that with variable parameters.
-
Composition: Data Type +... In fact, it's the data type [] that is, int []
-
Example
package Collection; public class demo9 { public static void main(String[] args) { System.out.println(sum1(5,6,7)); System.out.println(sum2(2,1,2)); System.out.println(sum3(1,4)); } //Summation //Through variable parameters public static int sum1(int... a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum+=a[i]; } return sum; } //2. When there are multiple parameters including variable parameters, variable parameters must be placed at the end, and at most one variable parameter can be used in a method. public static int sum2(float b,int... a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum+=a[i]; } return sum; } //3. When the method with variable parameters is overloaded with the method with fixed parameters, the order of invocation takes precedence over that with variable parameters. public static int sum3(int a, int b) { System.out.println("a"); int sum = 0; return sum; } public static int sum3(int... a) { System.out.println("b"); int sum = 0; return sum; } }
Enhanced for cycle
You can traverse arrays, collections, Maps. But Maps cannot traverse directly.
- Principle: After each traversal begins, an element is automatically extracted from the array and placed in the previous variable, which is the element used in the operation of the next loop.
- After the traversal is complete, a second traversal is automatically performed. All elements are traversed until the end of the array. The loop stops.
* For (Element: Array / Collection){ * Content * }
Example
package Collection; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class demo10 { public static void main(String[] args) { //foreach int arr[] = {4,5,7,9,9}; for(int i : arr) { System.out.println(i); } //Traversing Collection ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("java"); arrayList.add("java1"); arrayList.add("java2"); arrayList.add("java3"); arrayList.add("java4"); System.out.println(arrayList); for(String string : arrayList) { System.out.println(string); } //Traversing Map HashMap<String,String> map = new HashMap<>(); map.put("05", "iOS"); map.put("01", "java"); map.put("02", "html"); map.put("03", "BigData"); map.put("02", "iOS");//Overrides the previous values for(String key : map.keySet()) { System.out.println(key); } for(Map.Entry<String,String> entry : map.entrySet()) { System.out.println(entry); } } }
Collections class
Tools that encapsulate a large number of operations on Collection
Example
public class Demo18 { public static void main(String[] args) { //Requirements: Store multiple data, sortable, repeatable ArrayList<String> list = new ArrayList<>(); list.add("java"); list.add("java1haha"); list.add("java2BigData"); list.add("java3ok"); list.add("java2"); System.out.println(list); //Sorting with Collections //The first sort: sort by dictionary by default //Note: In order for the elements in the list to be sorted by dictionary, the elements must implement the Comparable interface Collections.sort(list); System.out.println("Default Dictionary Sorting:"+list); //Sort from short to long //Using comparators ComStrWithLength1 comStrWithLength = new ComStrWithLength1(); Collections.sort(list, comStrWithLength); System.out.println("Ranking from short to long:"+list); //Sort by length to length Comparator<String> comparator1 = Collections.reverseOrder(comStrWithLength); Collections.sort(list, comparator1); System.out.println("Ranking from long to short:"+list); //Recursive Dictionary Sorting Comparator<String> comparator2 = Collections.reverseOrder(); Collections.sort(list, comparator2); System.out.println("Recursive Dictionary Sorting:"+list); Collections.reverse(list); System.out.println("Reverse Sorting of Existing Sequences:"+list); //Maximum String max = Collections.max(list, comStrWithLength); System.out.println(max); } } class ComStrWithLength1 implements Comparator<String>{ @Override public int compare(String o1, String o2) { int num = o1.length()-o2.length(); return num==0?o1.compareTo(o2):num; } }