The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java 泛型在什么情况下不能使用

1. preface

Java 1.5 Generics are introduced to ensure type safety, prevent type conversion exceptions from occurring at run time, make types parameterized, and improve code readability and reuse rate. However, generics are not allowed in some cases. Today, I will summarize some scenarios where generics cannot be used in coding.

2. Basic types cannot use generics directly

The following writing is wrong:

// error 
Map<int,char> wrong= new HashMap<>()

Basic types cannot be used as generic types, and their corresponding wrapper classes need to be used.

// OK
Map<Integer,Character> wrong= new HashMap<>()

3. Generic types cannot be directly instantiated

A generic type can be understood as an abstract type, but only represents the abstraction of the type, so we cannot directly instantiate it, and the following is also wrong:

 public <E> E first(List<E> list){
     // error 
        E e = new E();
       return list.get(0);   
 }

4. Generics cannot be used as static variable types

Java Static types in are instantiated as the class is loaded, and the specific type of the generic type is not declared at this time. At the same time, because static variables are shared variables for all objects, their type can only be determined when a class is instantiated or a method is called. If it is a generic type, its type cannot be determined. Similarly, generics declared on a class cannot appear as return value types in static methods of the class. The following is also wrong:

public class Generic<T>{
    //cannot treat generic types declared by classes as static variables
    public static T t;
    //You cannot use generic types declared by a class as the return value of a static method
    public  static  T  rtval(List<T> list){
        return list.get(0);
    }
}

5. Inability to make instanceof judgment

Java The generics in is pseudo-generics and will be erased during compilation time. There is no generics in the running bytecode, so the following judgment conditions cannot be made:

public static <E> void wrong(List<E> list) {
    // error 
    if (list instanceof ArrayList<Integer>) {   
    }
}

But generic unbounded wildcard characters <?& gt; may be made instanceof Judgment, you think carefully why.

6. Unable to create an array of parameterized types

First of all, the following writing is correct:

// OK
List[] arrayOfLists = new List[2];

But if generics are added, the compilation will not pass:

//error
List<Integer>[] arrayOfLists = new List<Integer>[2];

Failure to do so will cause the following logical errors:

//If the above is true, the following should also be true
Object[] stringLists = new List<String>[];  
//Then we can put in the string List
stringLists[0] = new ArrayList<String>();   
//Put in Integer list
stringLists[1] = new ArrayList<Integer>();
//This is obviously unreasonable

7. Throwable cannot be extended directly or indirectly

The following two ways of writing will cause compilation errors:

//Throwable cannot be indirectly extended   
class IndirectException<T> extends Exception {}     

//Throwable cannot be extended directly  
class DirectException<T> extends Throwable {} 

If established, it will appear:

 try {
        // ...
    } catch (T e) {   
        //The type is uncertain and cannot handle specific exception logic
    }

How can you handle exceptions specifically is obviously not convenient for precise exception handling logic. But you can throw an indeterminate exception, but you cannot use generics of class declarations in static methods either:

class Parser<T extends Exception> {
   //This is right
    public void okThrow(File file) throws T {      
        // ...
    }
    //Static methods cannot have generic types declared by the class as return values and exceptions
    public static void wrongThrow(File file) throws T {      
    }
}

8. Methods that sign the same parameter after generic erase cannot be overloaded

Due to generic erasure, the following are not considered overloading of methods and cannot be compiled:

public class NoReload {
    public void sets(Set<String> strSet) { }
    public void sets(Set<Integer> intSet) { }
}

9. summary

Today summed up Java Although the IDE prompts will tell us some misunderstandings about the use of generics, these are also some knowledge points that we often ignore. If there are any deficiencies, please leave a message to correct them.

read more
Resource download
PriceFree
使用用途仅限于测试、实验、研究为目的,禁止用于一切商业运营,本团队不承担使用者在使用过程中的任何违法行为负责所有源码请自测!不保证你源码完整性有效性所有源码都是全网搜集。客服QQ: 138338438
Original link:https://bcbccb.cn/en/4610.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1
海外电子游戏竞猜 電子游戲 八国语言50种游戏 完整控制 BTC虚拟币支付 搭建教程
Overseas video games quiz video games in eight languages, 50 games, complete control of BTC virtual coin payment construction tutorial
Someone bought it 5 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish