Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the Java generic method

Shulou Source: shulou.com Published: 2022-05-31 10:37:27 11月24日 Update

The knowledge of this article "how to use Java generic method" is not understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use Java generic method" article.

Generic method

The general definition is as follows, that is, the method is preceded by a

Public class FTest {public List f (T t) {...};}

There are three ways to infer generic parameters:

1. Add certain generics directly before f ()

FTest.f (xxx)

2. Determined by input parameters, the following inference is Integer

Int number = 0bot fTest.f (number)

3. It can be determined by the return value.

List list = fTest.f (xxx)

Q: what's wrong with the following code? Is that where toString () is?

Public class A {public static void test (T t) {System.out.println (t.toString ());}}

A:test is a static method, so you can't perceive T in An instance.

Need to be changed to

Public static void test (T t)

There is no problem with toString (). ToString is the method of Object.

Generic parameters and type elimination

Q: what does the generic parameter T become at run time?

A: unified to Object and does not contain any type of information.

Q: can the generic parameter T be compared using instanceof?

Class A {void f (Object arg) if (arg instanceof T) {...}}

A: no, the compiler will report an error.

Q: can the generic parameter T be operated by new T () or new T []?

A: no, the compiler will report an error.

Q: can I call a method in a generic parameter object?

T.f ()

A: only methods of Object can be called.

Q: can I use T for forced conversion?

T t = (T) object

A: it works, but it doesn't really transform, and waring warnings are triggered at compile time.

Problems when creating a new generic object

Suppose there are two classes, the base class Parent and the subclass Child

Class Parent {} class Child extends Parent {}

Answer the following questions:

Q: is there a problem with the following sentence?

List list = new ArrayList ()

A: if there is a problem, the compilation will be wrong. There is no parent-child relationship between List and ArrayList.

Q:

List

Tags: Parameters inputs methods compilation content objects compilers problems subclasses containers are in will report things principles best run code elements that is features Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Huawei OPPO Reno Docker MariaDB