Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the problems that Java generics should pay attention to?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the problems that Java generics need to pay attention to". In the daily operation, I believe that many people have doubts about the problems that Java generics need to pay attention to. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions that Java generics need to pay attention to. Next, please follow the editor to study!

Generics related problems

1. Generic type reference passing problem

Reference passing in the form of the following is not allowed in Java:

ArrayList arrayList1=new ArrayList (); / / compilation error ArrayList arrayList1=new ArrayList (); / / compilation error

Let's first look at the first situation and expand the first situation into the following form:

ArrayList arrayList1=new ArrayList (); arrayList1.add (new Object ()); arrayList1.add (new Object ()); ArrayList arrayList2=arrayList1;// compilation error

In fact, at line 4, there will be a compilation error. So, let's assume it compiled correctly. So when we use the arrayList2 reference to take the value with the get () method, all objects of type String are returned, but we have actually stored objects of type Object in it, so there will be ClassCastException. So in order to avoid this highly prone error, Java does not allow such reference passing. This is also the reason why generics appear, that is, in order to solve the problem of type conversion, we can't go against its original intention.

Looking at the second situation, expand the second situation to the following form:

ArrayList arrayList1=new ArrayList (); arrayList1.add (new String ()); arrayList1.add (new String ()); ArrayList arrayList2=arrayList1;// compilation error

Yes, this situation is much better than the first case, at the very least, there is no ClassCastException when we use arrayList2, because it is a conversion from String to Object. However, what's the point of doing this? the reason for generics is to solve the problem of type conversion. We use generics, but in the end, we still have to make strong changes on our own, which goes against the original intention of generic design. So java doesn't allow it. Besides, if you use arrayList2 to add () a new object, how do I know if it's of type String or type Object when I get it? Therefore, pay special attention to the problem of reference passing in generics.

2. Generic type variables cannot be basic data types

For example, there is no ArrayList, only ArrayList. Because when the type is erased, the type variable (T) in the original class of ArrayList is replaced with Object, but the Object type cannot store the double value.

3. Runtime type query

ArrayList arrayList=new ArrayList (); if (arrayList instanceof ArrayLi

Because after the type is erased, the ArrayList is left with the original type, and the generic information String no longer exists.

4. Problems of generics in static methods and static classes

Static methods and static variables in a generic class cannot use generic type parameters declared by a generic class

Public class Test2 {public static T one; / / compilation error public static T show (T one) {/ / compilation error return null;}}

Because the instantiation of generic parameters in a generic class is specified when defining a generic type object, such as ArrayList, static variables and static methods do not need to be called with an object. Objects have not been created, how to determine the type of this generic parameter, so of course it is wrong.

But be careful to distinguish one of the following situations:

Public class Test2 {public static T show (T one) {/ / this is the correct return null;}}

Because this is a generic method, the T used in the generic method is the T defined in the method, not the T in the generic class.

Generic related interview questions

1. What are generics in Java? What are the benefits of using generics?

Generics are a mechanism for parameterized types. It can make the code applicable to various types, thus writing more general-purpose code, such as collection frameworks. Generics are a compile-time type validation mechanism. It provides compile-time type safety, ensures that only objects of the correct type can be used on generic types (usually generic collections), and avoids ClassCastException at run time.

2. How does Java generics work? What is type erasure?

The normal work of generics depends on the compiler checking the type first, then erasing the type and inserting the relevant instructions of casting where the type parameters appear.

The compiler erases all type-related information at compile time, so there is no type-related information at run time. For example, List is represented by only one List type at run time. Why erase it? This is to avoid type inflation.

3. What are qualified and unqualified wildcards in generics?

Qualified wildcards restrict types. There are two qualified wildcards, one of which represents an unqualified wildcard because it can be replaced by any type.

4. What is the difference between List and List?

This problem looks very similar to the previous one, but in fact it is completely different. List is an unknown type of List, while List is actually any type of List. You can assign List and List to List, but not List to List.

List listOfAnyType; List listOfObject = new ArrayList (); List listOfString = new ArrayList (); List listOfInteger = new ArrayList (); listOfAnyType = listOfString; / / legal listOfAnyType = listOfInteger; / / legal listOfObjectType = (List) listOfString; / / compiler error-in-convertible ty

13. The difference between List and the original type List.

The question is similar to "what's the difference between a primitive type and a type with parameters?" Types with parameters are type-safe, and their type safety is guaranteed by the compiler, but the original type List is not type-safe. You cannot store any type of Object other than String in a List of type String, and you can store any type of object in the original List. With generic types with parameters, you don't need type conversions, but for primitive types, you need to do explicit type conversions.

List listOfRawTypes = new ArrayList (); listOfRawTypes.add ("abc"); listOfRawTypes.add (123); / / Compiler allows this-but the exception String item = (String) listOfRawTypes.get (0); / / requires explicit type conversion item = (String) listOfRawTypes.get (1); / / throws ClassCastException because Integer cannot be converted to String List listOfString = new ArrayList (); listOfString.add ("abcd"); listOfString.add (1234) / / compilation error, which is better than throwing an exception at run time item = listOfString.get (0); / / No explicit type conversion is required-the compiler converts automatically

Wildcard character

Wildcard upper bound

General use

Public class Test {public static void printIntValue (List list) {for (Object elem: list) System.out.print (elem + ""); System.out.println ();}

This makes it compatible with more output than just List, as follows:

List li = Arrays.asList (1,2,3); List ls = Arrays.asList ("one", "two", "three"); printList (li); printList (ls). At this point, the study of "what are the problems you need to pay attention to in Java generics" is over. I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report