当前位置:网站首页>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 OfSon
class
? 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
边栏推荐
- D24:divisor and multiple (divisor and multiple, translation + solution)
- Current detection circuit - including op amp current scheme
- D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
- The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
- Powerful blog summary
- C # basic knowledge (2)
- [MySQL] sql99 syntax to realize multi table query
- JDBC Technology
- Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
- [note] glide process and source code analysis
猜你喜欢
Qtoolbutton - menu and popup mode
In 2022, 6G development has indeed warmed up
Learning notes of raspberry pie 4B - IO communication (SPI)
Loop compensation - explanation and calculation of first-order, second-order and op amp compensation
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
Blue Bridge Cup -- guess age
IDENTITY
Idea integrates Microsoft TFs plug-in
How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
The difference between single power amplifier and dual power amplifier
随机推荐
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Gossip about redis source code 77
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Blue Bridge Cup -- guess age
Hcip day 12 notes
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
Errors taken 1 Position1 argument but 2 were given in Mockingbird
In 2022, 6G development has indeed warmed up
Es6~es12 knowledge sorting and summary
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Comment obtenir une commission préférentielle pour l'ouverture d'un compte en bourse? Est - ce que l'ouverture d'un compte en ligne est sécurisée?
Gossip about redis source code 75
Cgb2201 preparatory class evening self-study and lecture content
How about opening an account at Hengtai securities? Is it safe?
Runtime. getRuntime(). totalMemory/maxMemory()
Gossip about redis source code 78
D26: the nearest number (translation + solution)
Open 2022 efficient office, starting from project management
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
Unity shader visualizer shader graph