Catalog
JDK1.5 Mechanisms to come after
Nested traversal of collections
Collection Nested Cases (Heroes Alliance Cases)
Generics of Java
JDK1.5 Mechanisms to come after
Why are there generics?
Earlier Object types could accept any object type, but in practice, there was a problem with type conversion. There are also potential risks, so Java provides generics to solve this security problem.
generic paradigm
The idea is to advance the work of clarifying data types to compilation and to clarify data types when creating collections. This is a bit like passing data types as parameters, so generics are also called parameterized types.
generic class
- Define generics on classes
- Format; public class class name <generic type 1,...>
- Note: Generic types must be reference types
generic method
- Define generics in methods
- Format: public < generic type > return type method name (generic type.);
Reference code 1:
import java.util.ArrayList; import java.util.Iterator; public class GenericDemo1 { public static void main(String[] args) { //Create List Collection Object //JDK1. Type inference will occur automatically after 7 ArrayList list = new ArrayList(); //Add elements to a collection list.add("hello"); list.add("word"); list.add("java"); list.add("bigdata"); //Get Iterator Object Iterator<String> iterator = list.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); String s = (String)next; System.out.println(s); } } }
Output results:
hello
word
java
bigdata
Before we learn generics, iterator s return Object s. Here we will introduce the idea of generics.
Reference code 2:
import java.util.ArrayList; import java.util.Iterator; public class GenericDemo1 { public static void main(String[] args) { //Create List Collection Object //JDK1. Type inference will occur automatically after 7 ArrayList<String> list = new ArrayList<String>(); //Add elements to a collection list.add("hello"); list.add("word"); list.add("java"); list.add("bigdata"); //Upward Transition 10 -- int -- Integer // list.add(10); //Get Iterator Object Iterator<String> iterator = list.iterator(); while (iterator.hasNext()){ String next = iterator.next(); System.out.println(next + "---" +next.length()); } } }
Output results:
hello---5
word---4
java---4
bigdata---7
After referencing a generic, use our own generic type, and the following interator automatically refers to the type.
Note: Adding elements to a collection must be of the same type, transitioning up.
generic interface
- Define generics on interfaces
- Format: public interface interface name <generic type 1...>
Generic Wildcard <?>
- Any type, if not specified, is Object and any Java class
?extends E
- Downbound, E and its subclasses
?superE
- Upbound, E and its parent
Reference code:
Note: We want to create generic type classes
import java.util.ArrayList; public class GenericDemo2 { public static void main(String[] args) { //If only one type is used within a generic and the data type is specified, it must be written consistently before and after ArrayList<Animal> list1 = new ArrayList<Animal>(); ArrayList<Dog> list2 = new ArrayList<Dog>(); ArrayList<Object> list3 = new ArrayList<Object>(); //Generic Wildcard <?> //Any type, if not specified, is Object and any Java class ArrayList<?> objects1 = new ArrayList<Animal>(); ArrayList<?> objects2 = new ArrayList<Dog>(); ArrayList<?> objects3 = new ArrayList<Object>(); //What? extends E down-qualified, E and its subclasses ArrayList<? extends Animal> list4 = new ArrayList<Animal>(); ArrayList<? extends Animal> list5 = new ArrayList<Dog>(); ArrayList<? extends Animal> list6 = new ArrayList<Cat>(); // ArrayList<? extends Animal> list7 = new ArrayList<Object>(); //What? super E Upbound, E and its parent ArrayList<? super Animal> list7 = new ArrayList<Animal>(); ArrayList<? super Animal> list8 = new ArrayList<Object>(); // ArrayList<? super Animal> list9 = new ArrayList<Dog>(); } }
Dog and Cat classes require extended Animal classes
What? Extds E can only be qualified down, otherwise
What? Sup E can only be qualified up, otherwise
Animal:
public class Animal { }
Dog:
public class Dog extends Animal{ }
Cat:
public class Cat extends Animal { }
Enhance for
- Simplify traversal of arrays and collections
Format:
For (Element Data Type Variable: Array or Collection Collection){
You can simply use a variable, which is an element
}
Benefits: Simplified traversal
Note: The goal of the enhanced for is to determine if it is null
Enhanced for improvements to iterate through previous collection codes
Reference code 1:
import java.util.ArrayList; //Use it when you can use the enhanced for in the future to remove the yellow warning line public class ForDemo1 { public static void main(String[] args) { //Define an array int[] arr = {1,2,3,4,5,6}; //Ordinary for loop System.out.println("Use Normal for loop:"); for (int i = 0;i < arr.length;i++){ System.out.println(arr[i]); } System.out.println("==========================="); //Enhance for cycle System.out.println("Use Enhancement for Loop traversal:"); for (int x : arr) { System.out.println(x); } System.out.println("==========================="); //Create Collection Object ArrayList<String> strings = new ArrayList<>(); //Add elements to a collection strings.add("hello"); strings.add("world"); strings.add("java"); strings.add("bigdata"); strings.add("hadoop"); System.out.println("Use Enhancement for Traversing a collection:"); //Traversing a collection using an enhanced for loop for (String string : strings) { System.out.println(string); } } }
Output results:
Use a normal for loop:
1
2
3
4
5
6
===========================
Traverse using an enhanced for loop:
1
2
3
4
5
6
===========================
Traverse the collection using enhanced for:
hello
world
java
bigdata
hadoop
The result of the run shows that the desired output is achieved, but what if the traversed collection is empty?
So we need to decide if it's null before we go through it.
Reference code 2:
import java.util.ArrayList; //Use it when you can use the enhanced for in the future to remove the yellow warning line public class ForDemo1 { public static void main(String[] args) { //Define an array int[] arr = {1,2,3,4,5,6}; //Ordinary for loop System.out.println("Use Normal for loop:"); for (int i = 0;i < arr.length;i++){ System.out.println(arr[i]); } System.out.println("==========================="); //Enhance for cycle System.out.println("Use Enhancement for Loop traversal:"); for (int x : arr) { System.out.println(x); } System.out.println("==========================="); //Create Collection Object ArrayList<String> strings = new ArrayList<>(); //Add elements to a collection strings.add("hello"); strings.add("world"); strings.add("java"); strings.add("bigdata"); strings.add("hadoop"); System.out.println("Use Enhancement for Traversing a collection:"); //Determine whether a set element is null if (strings!=null){ for (String s : strings) { System.out.println(s); } } } }
Output results:
Use a normal for loop:
1
2
3
4
5
6
===========================
Traverse using an enhanced for loop:
1
2
3
4
5
6
===========================
Traverse the collection using enhanced for:
hello
world
java
bigdata
hadoop
Enhanced for loops are actually meant to replace iterators. How do you verify?
Use concurrent modification exception validation:
ConcurrentModificationException concurrent exception.
Testing of generic classes
Reference code:
Create the GenericTooll class:
/* Generic classes: Define generics on classes Format: public class class class name <generic type 1,...> Note: Generic types must be reference types The contents of <> here simply represent a parameter data type, which is a variable. Since it is a variable, it conforms to the rules for naming variables and can be any name that conforms to the rules for naming identifiers. */ public class GenericTooll<T> { private T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; } }
Create a GenericTest1 test class:
No generics, Object type by default
Must be consistent with generic class types
/* Testing of generic classes */ public class GenericTest1 { public static void main(String[] args) { GenericTooll<String> gt1 = new GenericTooll<>(); gt1.setObj("java"); String obj = gt1.getObj(); System.out.println(obj); } }
Testing generic methods
Reference code:
Create the GenericTool2 class:
/* generic method Define generics in methods Format: public <generic type>return type method name (generic type.) */ public class GenericTool2 { public <T> void show(T t){ System.out.println(t); } }
Create a GenericTest2 test class:
public class GenericTest2 { public static void main(String[] args) { //create object GenericTool2 gt = new GenericTool2(); gt.show("hadoop"); gt.show("23"); gt.show(true); } }
Output results:
hadoop
23
true
Testing generic interfaces
Create the GenericTool3 interface:
public interface GenericTool3<T> { public abstract void show(T t); }
Create the GenericTool3Impl interface class:
public class GenericTool3Impl<T> implements GenericTool3<T>{ @Override public void show(T t) { System.out.println(t); } }
Create a GenericTest3 test class:
public class GenericTest3 { public static void main(String[] args) { GenericTool3Impl<String> sgt1 = new GenericTool3Impl<>(); sgt1.show("hadoop"); } }
Output results:
hadoop
Nested traversal of collections
Before we learned generics, we created methods to call:
public class ArgsDemo { public static void main(String[] args) { //Sum two numbers int a = 10; int b = 20; // System.out.println(a+b); sum(a, b); //Sum three numbers int c = 30; sum(a, b, c); //Sum Four Numbers int d = 40; sum(a, b, c, d); } public static void sum(int a, int b) { System.out.println(a + b); } public static void sum(int a, int b, int c) { System.out.println(a + b + c); } public static void sum(int a, int b, int c, int d) { System.out.println(a + b + c + d); } }
Output results:
30
60
100
What if we were not sure how many we would sum? What do you do at this time?
According to our case, the method name is the same, the data type in the parameter list is the same, but the number is different. At this time, every parameter added, the method needs to be written new, which is very troublesome. What can I do?
java takes this into account and provides us with a technology: variable parameters
Overview: Use when defining methods and when parameters are uncertain
Format: Type method name (data type... variable name) of modifier return value {}
Note: The variable here is actually an array. If a method has variable parameters and more than one parameter, then the variable parameter must be the last one
A method in the Arrays tool class
public static <T> List<T> List<T> asList(T... a)
Code improvements using methods in the Arrays tool class
Define the addition method in the form of variable parameters:
Reference code:
public class ArgsDemo { public static void main(String[] args) { //Sum two numbers int a = 10; int b = 20; // System.out.println(a+b); sum(a, b); //Sum three numbers int c = 30; sum(a, b, c); //Sum Four Numbers int d = 40; sum(a, b, c, d); sum(312,123,1,312,13,13,13,13,13,1,34,5,4,3,131,3); } //Defining the addition method in the form of variable parameters public static void sum(int... ints){ int sum = 0; // System.out.println(ints); for(int i=0;i<ints.length;i++){ sum = sum + ints[i]; } System.out.println(sum); } }
Output results:
30
60
100
994
When a method is defined with both fixed values and variable number of parameters, the definition of variable parameters is placed last.
import java.util.Arrays; import java.util.List; public class ArgsDemo { public static void main(String[] args) { List<String> strings = Arrays.asList("hello", "world", "java", "bigdata"); for (String s : strings) { System.out.println(s); } sum("handsome young man",1998,10,21,2048); } public static void sum(String s,int... ints){ System.out.println(s); int sum = 0; for (int i = 0;i < ints.length;i++){ sum = sum + ints[i]; } System.out.println(sum); } }
Output results:
hello
world
java
bigdata
handsome young man
4077
Case 1
Requirements: Get 10 random numbers between 1 and 20, requirements cannot be repeated
Can arrays be implemented? Because the length is not good enough to determine, we choose the set.
Random package needs to be imported
Reference code:
import java.util.ArrayList; import java.util.Random; public class RandomTest { public static void main(String[] args) { //Create Random Number Object Random random = new Random(); //Create a collection object to store random numbers ArrayList<Integer> arr = new ArrayList<>(); //Define if there are 10 elements in a variable statistics set int count = 0; while (count < 10){ //Generate Random Numbers int i = random.nextInt(20) + 1; //Determine if there is this random number in the set if (!arr.contains(i)){ //Add a random number to a set arr.add(i); count++; } } System.out.println(arr); } }
Output results:
[10, 7, 14, 5, 18, 11, 19, 8, 20, 2]
[11, 5, 7, 16, 4, 1, 19, 9, 17, 10]
[13, 15, 3, 18, 4, 20, 5, 14, 6, 1]
Case 2
Requirements: The keyboard enters multiple data, ending with 0, requiring the maximum value in the multiple data to be output in the console.
Reference code:
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; /* Keyboard enters multiple data, ending with 0, requiring the console to output the maximum of the multiple data */ public class ArrayListTest { public static void main(String[] args) { //Create keyboard entry object Scanner sc = new Scanner(System.in); //Create a collection to store data entered by the keyboard ArrayList<Integer> arr = new ArrayList<>(); while (true){ int num = sc.nextInt(); if (num==0){ break; }else { arr.add(num); } } //There is a method sort() in the Array tool class //Set to Array Object[] objects = arr.toArray(); Arrays.sort(objects); //The first is the minimum Integer minNumber = (Integer) objects[0]; //Last is maximum Integer maxNumber = (Integer)objects[objects.length - 1]; System.out.println("The minimum value is:" + minNumber); System.out.println("The maximum is:" + maxNumber); } }
Output results:
23
343
13
3252
612
631
6143
642
16
7
1
675
0
Minimum value: 1
Maximum: 6143
Collection Nested Cases (Heroes Alliance Cases)
Requirements: Summoner's Canyon has red and blue sides, red side has many heroes, blue side has many heroes, each hero is a Summoner object, can use a collection to represent Summoner's Canyon has 10 heroes.
The summoners in red and blue can be represented as a collection:
The hero of the red side: ArrayList < Hero > redList
The hero on the blue side: ArrayList<Hero>blueList
Whether it's red or blue, it's a hero in the Summoner's Canyon
The Summoners of Summoners Canyon can also be represented as a collection: ArrayList <ArrayList <Hero> LOL
This phenomenon is called nesting of sets.
Reference code:
Create a Hero object:
import java.util.Objects; public class Hero { private String name;//Summoner's name private String heroname;//Heroes //Define construction methods without parameters public Hero() { } //Define construction methods with parameters public Hero(String name, String heroname) { this.name = name; this.heroname = heroname; } //Define getXxx() and setXxx() methods public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHeroname() { return heroname; } public void setHeroname(String heroname) { this.heroname = heroname; } //Override toString method @Override public String toString() { return "Hero{" + "name='" + name + '\'' + ", heroname='" + heroname + '\'' + '}'; } //Override equals method @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Hero hero = (Hero) o; return Objects.equals(name, hero.name) && Objects.equals(heroname, hero.heroname); } }
Create a LOLHero test class:
import java.util.ArrayList; import java.util.Iterator; public class LOLHero { public static void main(String[] args) { //Define the collection of red summoners ArrayList<Hero> redList = new ArrayList<>(); //Define the collection of blue summoners ArrayList<Hero> blueList = new ArrayList<>(); //Define Summoner Canyon Collection ArrayList<ArrayList<Hero>> LOL = new ArrayList<>(); //Place the red and blue heroes in the Summoner's Canyon LOL.add(redList); LOL.add(blueList); //Create Red Square Heroes Hero h1 = new Hero("TheShay", "Dark Swordsman"); Hero h2 = new Hero("Spicy hot pot", "Nocturne"); Hero h3 = new Hero("The Great Devil", "The Master of Movie Flow"); Hero h4 = new Hero("UZI", "Night Hunter"); Hero h5 = new Hero("Liu Qingsong", "Steam Robot"); //Place the red hero in the Summoner's Canyon redList.add(h1); redList.add(h2); redList.add(h3); redList.add(h4); redList.add(h5); //Create Blue Square Heroes Hero h6 = new Hero("Santiago", "Saint Gun Rover"); Hero h7 = new Hero("Great Minister of War", "Void Reaver"); Hero h8 = new Hero("Coin Brother", "Outlier Sticks"); Hero h9 = new Hero("Draven", "Vincent"); Hero h10 = new Hero("Frog", "Soul Lock Warden"); //Place the blue hero in the Summoner's Canyon blueList.add(h6); blueList.add(h7); blueList.add(h8); blueList.add(h9); blueList.add(h10); //Iterator traversal Iterator<ArrayList<Hero>> LOLhero = LOL.iterator(); while (LOLhero.hasNext()){ ArrayList<Hero> heros = LOLhero.next(); Iterator<Hero> LOLheros = heros.iterator(); while (LOLheros.hasNext()){ Hero heros1 = LOLheros.next(); System.out.println(heros1); } } } }
Output results:
Hero{name='TheShay', heroname='Dark Swordsman'}
Hero{name='spicy pan', heroname='permanent nightmare'}
Hero{name='big devil', heroname='master of movies'}
Hero{name='UZI', heroname='Night Hunter'}
Hero{name='Liu Qingsong', heroname='Steam Robot'}
Hero{name='Saint Gun', heroname='Saint Gun Rover'}
Hero{name='Master', heroname='Void Predator'}
Hero{name='Coin Brother', heroname='Outlier Spur'}
Hero{name='Draven', heroname='Vincent'}
Hero{name='frog', heroname='lock warden'}
Did Draven play Vincent so hard?
🉑 Let's give Beauty a look! 🉑