当前位置:网站首页>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
边栏推荐
- Op amp related - link
- The interviewer's biggest lie to deceive you, bypassing three years of less struggle
- 2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination
- Recursive least square adjustment
- Mongoose the table associated with the primary key, and automatically bring out the data of another table
- A preliminary study on the middleware of script Downloader
- Es6~es12 knowledge sorting and summary
- Unity shader visualizer shader graph
- What are the securities companies with the lowest Commission for stock account opening? Would you recommend it? Is it safe to open an account on your mobile phone
- Fashion cloud interview questions series - JS high-frequency handwritten code questions
猜你喜欢
MLX90614 driver, function introduction and PEC verification
Fluent learning (5) GridView
Hcip 13th day notes
Actual combat | use composite material 3 in application
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Hcip day 16 notes
Qtoolbutton available signal
A treasure open source software, cross platform terminal artifact tabby
How to quickly build high availability of service discovery
Ppt image processing
随机推荐
33 restrict the input of qlineedit control (verifier)
Gossip about redis source code 73
Pointer concept & character pointer & pointer array yyds dry inventory
2.14 summary
C summary of knowledge point definitions, summary notes
Fluent learning (5) GridView
Bufferpool caching mechanism for executing SQL in MySQL
[MySQL] classification of multi table queries
[15th issue] Tencent PCG background development internship I, II and III (OC)
The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
How can I get the Commission discount of stock trading account opening? Is it safe to open an account online
Es6~es12 knowledge sorting and summary
炒股开户佣金优惠怎么才能获得,网上开户安全吗
D28:maximum sum (maximum sum, translation)
Subset enumeration method
NPM script
finalize finalization finally final
Day30-t540-2022-02-14-don't answer by yourself
Open 2022 efficient office, starting from project management
[untitled]