Home > Java > javaTutorial > body text

How to use wildcards in Java?

WBOY
Release: 2023-05-10 09:10:15
forward
1426 people have browsed it

1. Wildcard, represents an unknown type, which represents a type that you don’t care about or cannot determine the actual operation. It is generally used in conjunction with container classes.

public void testV(List<?> list) {}
Copy after login

2, , define the upper limit, during which only reading ability is available. This approach indicates that the parameterized type may be the specified type or a subtype.

//t1要么是Test2,要么是Test2的子类
public void testC(Test1<? extends Test2> t1) {
    Test2 value = t1.getValue();
    System.out.println("testC中的:" + value.getT());
}
Copy after login

3. , lower limit definition, with reading ability and partial writing ability, subclasses can write to the parent class. This method indicates that the parameterized type can be a specified type or a parent class.

//t1要么是Test5,要么是Test5的父类
public void testB(Test1<? super Test5> t1) {
    //子类代替父类
    Test2 value = (Test2) t1.getValue();
    System.out.println(value.getT());
}
Copy after login

Note on the use of wildcards

The form of wildcard characters and type parameters are often used together.

The form of type parameters can replace wildcard characters.

People who can use wildcards use wildcards because wildcards tend to be simpler in form and more readable.

The above is the detailed content of How to use wildcards in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template