当前位置:网站首页>Generic mechanism and enhanced for loop
Generic mechanism and enhanced for loop
2022-07-24 00:20:00 【@Code every day】
Author's brief introduction : Hello, I'm @ Typing code every day , A player of material transcoding farmer , Hope to work together , Progress together !
Personal home page :@ Every day, I have to type the personal homepage of the code
Recommend a simulated interview 、 Brush Title artifact , From basic to interview questions Click to jump to the question brushing website to register for learning
Catalog
First understand the generic mechanism
First understand the generic mechanism
️JDK5.0 New features introduced later : Generic
️ Generic This grammatical mechanism , Only works during the compilation phase of the program , Just for compiler reference ( Runtime generics are useless )
️ Used Generic benefits What is it? ?
First of all : The element types stored in the collection are unified .
second : The element type taken from the collection is the type specified by the generic , There is no need to do a lot of “ Move down ”!️ The disadvantages of generics What is it? ?
Leads to a lack of diversity in the elements stored in the collection !
️ example 1: The usage of generics
For generics, the scope is reduced , For a set, we can add any type of element ; When we call the iterator next() When the method is used , The type taken out is actually Object type ; We need to transform downward to call the methods in the class ; But if we specify a generic scope , There is no need to transform downward , Accessing the types of other ranges will result in an error ! Let's feel it through an example !
package com.bjpowernode.javase.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest01 {
public static void main(String[] args) {
//1. Don't use generics
List mylist = new ArrayList();
//1.1. Create objects
Cat c = new Cat();
Bird b = new Bird();
//1.2. Add objects to the collection
mylist.add(c);
mylist.add(b);
//1.3. Acquisition iterator , Traversal collection call move Method
Iterator it = mylist.iterator();
while(it.hasNext()){
// The default object is Object type ;Object There's no move() Method
Object obj = it.next();
// Move down
if(obj instanceof Animal){
Animal animal = (Animal)obj;
animal.move();
}
}
//2. Use generics
// Use generics List<Animal> after , Express List Only storage is allowed in the collection Animal Data of type .
// Use generics to specify the data types stored in the collection .
List<Animal> mylist = new ArrayList<Animal>();
//2.1. Create objects
Cat c = new Cat();
Bird b = new Bird();
//2.2. Add elements
mylist.add(c);
mylist.add(b);
//2.3. Acquisition iterator , Traversal call move Method
// This represents iterator iteration Animal type .
Iterator<Animal> it = mylist.iterator();
while(it.hasNext()){
// Use generics <Animal>, The extracted element is Animal type
Animal animal = it.next();
// There's no need to move down , Call directly
animal.move();
// However, calling methods specific to subclasses still requires a downward transformation , It just facilitates a link
if(animal instanceof Cat){
Cat cat = (Cat)animal;
cat.catchMouse();
}
if(animal instanceof Bird){
Bird bird = (Bird)animal;
bird.fly();
}
}
}
}
class Animal {
// Parent class's own method
public void move(){
System.out.println(" Animals are moving !");
}
}
class Cat extends Animal {
// Unique method
public void catchMouse(){
System.out.println(" Cat catches mouse !");
}
}
class Bird extends Animal {
// Unique method
public void fly(){
System.out.println(" The birds are flying !");
}
}
️ example 2: Automatic type inference
JDK8 And then introduced : Automatic type inference mechanism .( Also known as diamond expression )
package com.bjpowernode.javase.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest02 {
public static void main(String[] args) {
// ArrayList< The type here automatically infers >(), Premise is JDK8 After that .
List<Animal> myList = new ArrayList<>(); // Automatic type inference
// Add objects to the collection
myList.add(new Animal());
myList.add(new Cat());
myList.add(new Bird());
// Traverse
Iterator<Animal> iterator = myList.iterator();
while(iterator.hasNext()){
Animal an = iterator.next();
an.move();
}
// In such as : Only exist String A collection of types
List<String> str = new ArrayList<>(); // Automatic type inference
str.add("http://www.126.com");
str.add("http://www.baidu.com");
str.add("http://www.bjpowernode.com");
//str.add(new String(123)); // error , Type mismatch
System.out.println(str.size()); //3
// Traverse
Iterator<String> it2 = str.iterator();
while(it2.hasNext()){
// If you don't use generics , We also need to judge whether it is a String
Object obj = it2.next();
if(obj instanceof String){
String ss = (String)obj;
ss.substring(7);
}
// Use generic expressions , Directly through the iterator String Data of type
String s = it2.next();
// Call directly String Class substring Method intercepts the string .
String newString = s.substring(7);
System.out.println(newString);
}
}
}
Custom generics
️ With the above understanding of generics , Can we make our own defined classes have the feature of generics ? Let's customize generics !
️ When you customize generics ,<> In angle brackets is an identifier , Write casually .
java What often appears in the source code is :<E> and <T>
E yes Element Word initials .
T yes Type Word initials .
package com.bjpowernode.javase.collection;
// Custom generics
public class GenericTest03<E> { //E Just the identifier , Write casually , General writing E perhaps T
// Provide a method , Pay attention to the internal parameters
public void doSome(E e){
System.out.println(e);
}
// Program entrance
public static void main(String[] args) {
//1、 Create objects , If this method can only be called String type
GenericTest03<String> gt = new GenericTest03<>(); // Automatic type inference
//gt.doSome(10); // Type mismatch
gt.doSome("abc"); // This method can only pass parameters with String type
// Create objects , If this method can only be called Integer type
GenericTest03<Integer> gt2 = new GenericTest03<>();
//gt2.doSome("abc"); // Type mismatch
gt2.doSome(100); // Automatic boxing
//2、 Define a method , The returned type should be consistent with the generic type of the class
MyIterator<String> mt = new MyIterator<>();
String str = mt.get(); // The return type can only be String
MyIterator<Animal> mt2 = new MyIterator<>();
Animal an = mt2.get(); // The return type can only be Animal
//3、 We don't need to define generics , The parameter is Object type
GenericTest03 gt3 = new GenericTest03();
gt3.doSome(new Object()); // The parameter is Object type
}
}
class MyIterator<T>{
public T get(){
return null;
}
}enhance for loop (foreach)
️JDK5.0 Then a new feature was introduced : be called enhance for loop , Or called foreach
️ We have learned for loop , So what is enhancement for Circulation? ? Let's first look at grammar :
for( Element type Variable name : Array or collection ){ System.out.println( Variable name ); }️ enhance for Cyclic shortcoming : No subscript !
package com.bjpowernode.javase.collection;
public class ForEachTest01 {
public static void main(String[] args) {
// 1. Define an array
int[] arr = {22,3,9,5,6,8};
// 2. Traversal print ( Ordinary for loop )
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// 3. enhance for loop
for(int i:arr){
// foreach There is a drawback : No subscript . In a loop that requires subscripts , Enhancement is not recommended for loop .
// i It's the elements in the array ( Every element in the array )
System.out.println(i);
}
}
}
️ example : Use together foreach
For sets with subscripts , Now we have learned three printing methods : iterator 、 Use subscripts 、foreach
package com.bjpowernode.javase.collection;
import java.util.*;
// Use together foreach
public class ForEachTest02 {
public static void main(String[] args) {
// establish List aggregate
List<String> strList = new ArrayList<>();
// Add elements
strList.add("hello");
strList.add("world");
strList.add("kitty");
//1. Traverse , Using Iterators
Iterator<String> it = strList.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
//2. Use subscript mode
for (int i = 0; i < strList.size(); i++) {
System.out.print(strList.get(i)+" ");
}
System.out.println();
//3. Use foreach
// Because generics use String type , So it is :String s
for (String s:strList) {
System.out.print(s+" ");
}
}
}
Conclusion
Today's sharing is here ! Register and join the problem brushing army through the link below ! All kinds of big factory interview questions are waiting for you !
Brush Title artifact , From basic to interview questions Click to jump to the website
边栏推荐
- 进步成长的快乐
- English grammar_ Demonstrative pronoun - so
- Gbase 8C session information function (6)
- English语法_指示代词 -such / the same
- Delete all data of specified query criteria in Oracle
- Nacos
- Nacos
- GBase 8c 访问权限查询函数(三)
- Comparison of the shortcomings of redis master-slave, sentinel and cluster architectures
- GBase 8c访问权限查询函数(六)
猜你喜欢

Redis cluster hash sharding algorithm (slot location algorithm)

mongodb的多数据源配置

Write all the code as soon as you change the test steps? Why not try yaml to realize data-driven?

Redis master-slave synchronization mechanism

L2TP的LAC自动拨号实验

IIS deployment.Netcore

Tencent will close the "magic core". Is there any resistance to the development of digital collections?

iNFTnews | 呵护“雪山精灵”,42VERSE“数字生态保护”公益项目即将盛启

OA项目之我的会议(查询)

腾讯将关闭“幻核”,数字藏品领域发展是否面临阻力?
随机推荐
盘点为下个牛市做准备的10个新Layer1
As a programmer, is there anything you want to say to the newcomer?
GBase 8c 会话信息函数(五)
English grammar_ Demonstrative pronoun -such / the same
Redis 集群hash分片算法(槽位定位算法)
腾讯将关闭“幻核”,数字藏品领域发展是否面临阻力?
Jenkins uses sonarqube to build pipeline code review project
GBase 8c模式可见性查询函数(二)
docker搭建sonarqube,mysql5.7环境
Gbase 8C access authority query function (II)
GBase 8c 访问权限查询函数(五)
Xmind用例导入到TAPD的方案(附代码)
Distributed cap principle
PHP implements stripe subscription
Gbase 8C access authority query function (I)
Redis持久化机制RDB、AOF
投资的物质回报
The differences between text and image drawing, data storage, localstorage, sessionstorage, and cookies
paypal订阅流程及api请求
YOLOv1