当前位置:网站首页>Generic tips
Generic tips
2022-07-03 23:28:00 【Carbon water carbon water】
Generic Tips
Tips
- Generics can be used all the way , If you don't need it, don't use it all the way
- Static methods cannot use generics
- Exception classes cannot be declared as generic classes
- A class wants to use generics , You must bring generics when this class is defined
- The type of a generic must be a class , Cannot be a basic data type . Where basic data types are needed , Replace with packing
- If a generic class is defined , Instantiation does not indicate the generic type of the class , The generic type is considered to be Object type , But not equal to Object type
Suggest : Indicates the generic type of the class when instantiated - The parent class has a generic type , Subclasses can choose to keep generics or specify generic types
// Parent class
class Father<T1, T2> {
}
// Subclass
//AB by Son Own required generics
// Subclasses do not retain the generics of the parent class
// 1) There is no type erase
class Son<A, B> extends Father{
// Equivalent to class Son extends Father<Object,Object>{}
}
// 2) The specific type
class Son2<A, B> extends Father<Integer, String> {
}
// Subclasses retain the generics of the parent class
// 1) Keep it all
class Son3<T1, T2, A, B> extends Father<T1, T2> {
}
// 2) Partial reservation
class Son4<T2, A, B> extends Father<Integer, T2> {
}
- References of different generics cannot be assigned to each other
- aggregate After specifying the specific generic type , In a collection class or interface, whenever a class or interface is defined , internal structure ( such as : Method 、 Constructors 、 Properties, etc ) Where to use generics of classes , Are specified as instantiated generic types .
List<? extends T> and List <? super T> What's the difference? ?
List<? extends T> // Any inheritance from T The type of List,
List<? super T> // Any T Made up of List.
for example List<? extends Number> // Acceptable List<Integer> or List<Float>.
wildcard
E- Element ( Use... In a collection , Because there are elements in the collection )T- Type(Java class )K- Key( key )V- Value( value )N- Number( value type )?- To express uncertainty java type , It's a type wildcard , Represents all types of
about List<?> You can't add data to it , In addition to adding null outside .
Allow data to be read , The type of data read is Object- The use of restricted wildcards .
? extends A:G<? extends A>It can be used asG<A>andG<B>Parent class of , among B yes A OfSonclass
? super A:G<? super A>It can be used asG<A>andG<B>Parent class of , among B yes A Of Father class
// It's easy to get wrong
List<? extends Person> list1 = null;
// Compile not pass
list1.add(new Student());
// because <? extends Person> representative Person Subclasses of ,Student It's also Person Subclasses of
// here ? And Student The size of cannot be judged , So compilation errors
Generic methods
- Generic methods , Can be declared static . reason : Generic parameters are determined when the method is called . Not determined when instantiating a class .
- Generic methods : There is a generic structure in the method , Generic parameters have nothing to do with the generic parameters of the class .
let me put it another way , It doesn't matter whether the generic method belongs to a generic class or not .
// Generic methods
public static <E> List<E> copyFromArrayToList(E[] arr){
ArrayList<E> list = new ArrayList<>();
for(E e : arr){
list.add(e);
}
return list;
}
// Call generic methods
public void test4(){
Order<String> order = new Order<>();
Integer[] arr = new Integer[]{
1,2,3,4};
// When a generic method is called , Indicates the type of the generic parameter .
List<Integer> list = order.copyFromArrayToList(arr);
System.out.println(list);
}
Inheritance of generics
if class A yes class B Parent class of , be
G<A>andG<B>They don't have the relationship of children and parents , The two are juxtaposed , The common parent is :G<?>
for example :List<Object>List<String>A<G>yesB<G>Parent class of
for example :List<String>AbstractList<String>
//main
public static void main(String[] args) {
// Because a subclass inherits a generic parent class , Indicates the generic type . When instantiating a subclass object , No longer need to specify generics .
SubOrder sub = new SubOrder(); //SubOrder It's not a generic class , Instantiate without adding <>
sub.setOrderT(123);
// sub.setOrderT("1");// The error type does not conform to
SubOrder1<String> sub1 = new SubOrder1<>(); //SubOrder1 It's a generic class , Instantiation requires adding <>
sub1.setOrderT("order2...");
}
// Parent class
public class Order<T> {
String orderName;
int orderId;
T orderT;// The internal structure of the class can use the generics of the class
public Order(){
// Compile not pass Only know T Only when the specific class of new
// T[] arr = new T[10];
T[] arr = (T[]) new Object[10];
}
public Order(String orderName,int orderId,T orderT){
this.orderName = orderName;
this.orderId = orderId;
this.orderT = orderT;
}
// None of the following three methods are generic methods
public T getOrderT(){
return orderT;
}
public void setOrderT(T orderT){
this.orderT = orderT;
}
@Override
public String toString() {
return "Order{" +
"orderName='" + orderName + '\'' +
", orderId=" + orderId +
", orderT=" + orderT +
'}';
}
}
// Subclass 1
public class SubOrder extends Order<Integer> {
//SubOrder: It's not a generic class
public static <E> List<E> copyFromArrayToList(E[] arr){
ArrayList<E> list = new ArrayList<>();
for(E e : arr){
list.add(e);
}
return list;
}
// Subclass 2
public class SubOrder1<T> extends Order<T> {
//SubOrder1<T>: Still a generic class
}
To be solved
Generic erase
边栏推荐
- Hcip day 14 notes
- Exclusive download! Alibaba cloud native brings 10 + technical experts to bring "new possibilities of cloud native and cloud future"
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Design of logic level conversion in high speed circuit
- Text replacement demo
- Overview of Yunxi database executor
- Hcip day 16 notes
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Tencent interview: can you pour water?
- Take you to master the formatter of visual studio code
猜你喜欢

Current detection circuit - including op amp current scheme

Schematic diagram of crystal oscillator clock and PCB Design Guide

How to quickly build high availability of service discovery

Hcip day 15 notes

Format cluster and start cluster

How to write a good title of 10w+?

Exclusive download! Alibaba cloud native brings 10 + technical experts to bring "new possibilities of cloud native and cloud future"

A treasure open source software, cross platform terminal artifact tabby

Shiftvit uses the precision of swing transformer to outperform the speed of RESNET, and discusses that the success of Vit does not lie in attention!

In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
随机推荐
Hcip 13th day notes
Hcip day 16 notes
Recursive least square adjustment
Sword finger offer day 4 (Sword finger offer 03. duplicate numbers in the array, sword finger offer 53 - I. find the number I in the sorted array, and the missing numbers in sword finger offer 53 - ii
Alibaba cloud container service differentiation SLO hybrid technology practice
Shell script three swordsman awk
Maxwell equation and Euler formula - link
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Enter MySQL in docker container by command under Linux
Hcip day 12 notes
User login function: simple but difficult
[network security] what is emergency response? What indicators should you pay attention to in emergency response?
Gossip about redis source code 74
Pandaoxi's video
Qtoolbutton - menu and popup mode
Blue Bridge Cup -- Mason prime
Live app source code, jump to links outside the station or jump to pages inside the platform
Go error collection | talk about the difference between the value type and pointer type of the method receiver
QT creator source code learning note 05, how does the menu bar realize plug-in?
ThreadLocal function, scene and principle