当前位置:网站首页>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
边栏推荐
- Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
- Take you to master the formatter of visual studio code
- Xiangong intelligent obtained hundreds of millions of yuan of b-round financing to accelerate the process of building non-standard solutions with standardized products
- [network security] what is emergency response? What indicators should you pay attention to in emergency response?
- Blue Bridge Cup -- guess age
- How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
- . Net ADO splicing SQL statement with parameters
- Open 2022 efficient office, starting from project management
- Runtime. getRuntime(). totalMemory/maxMemory()
- A preliminary study on the middleware of script Downloader
猜你喜欢

Pyqt5 sensitive word detection tool production, operator's Gospel

How to understand the gain bandwidth product operational amplifier gain

2/14 (regular expression, sed streaming editor)

Runtime. getRuntime(). totalMemory/maxMemory()

Shell script three swordsman awk

Pyqt5 sensitive word detection tool production, operator's Gospel

Es6~es12 knowledge sorting and summary

2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination

Ppt image processing

Unity shader visualizer shader graph
随机推荐
Day30-t540-2022-02-14-don't answer by yourself
Is the controller a single instance or multiple instances? How to ensure the safety of concurrency
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Take you to master the formatter of visual studio code
Powerful blog summary
[note] IPC traditional interprocess communication and binder interprocess communication principle
D25:sequence search (sequence search, translation + problem solving)
D28:maximum sum (maximum sum, translation)
炒股開戶傭金優惠怎麼才能獲得,網上開戶安全嗎
Open 2022 efficient office, starting from project management
Idea integrates Microsoft TFs plug-in
Unsafe and CAS principle
Simple solution of m3u8 file format
In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
Blue Bridge Cup -- Mason prime
Pointer concept & character pointer & pointer array yyds dry inventory
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
Live app source code, jump to links outside the station or jump to pages inside the platform
Current detection circuit - including op amp current scheme
Unity shader visualizer shader graph