search
HomeJavajavaTutorialGeneric wildcards in Java functions: upper and lower bounds

In Java, generic wildcards allow generic types to be represented without specifying specific types. The upper bound wildcard character ( extends T>) represents a type parameter T or any subclass thereof, allowing subclass data to be accepted in a list. The lower wildcard character ( super T>) represents T or any of its superclasses, allowing the superclass data in the list to be accepted. Wildcards can be used to implement resizable array lists with generics, allowing handling of various types and addition/removal operations.

Java 函数中的泛型通配符:上限和下限

Generic wildcards in Java functions: upper and lower bounds

In Java, we can use wildcards to represent generics Types allow us to use generics without specifying a specific type. This article will explore upper and lower wildcards and demonstrate their usage through practical examples.

Upper limit wildcard character

Upper limit wildcard character ( extends T>) represents the type parameter T or any of its subclasses kind. For example:

public static <T extends Number> double sum(List<T> numbers) {
  double total = 0;
  for (T num : numbers) {
    total += num.doubleValue();
  }
  return total;
}

This function can accept any Number (such as Integer, Double) or a list of its subclasses. We can safely pass any list that satisfies the Number constraint to this function as follows:

List<Integer> ints = List.of(1, 2, 3);
double sumIntegers = sum(ints); // 编译通过

Lower bound wildcard

Lower bound wildcard( super T>) represents the type parameter T or any of its superclasses. For example:

public static <T super Number> void process(List<T> entities) {
  for (T entity : entities) {
    System.out.println(entity.getClass().getName());
  }
}

This function can accept a list of any Number superclass (such as Object, Serializable). We can safely pass any list that satisfies the Number superclass constraints to this function as follows:

List<Object> objects = List.of("Hello", 123);
process(objects); // 编译通过

Practical Case

Consider a resizable array List, we can use generic wildcards to achieve it:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ResizableArrayList<E> {

  private List<E> list;

  public ResizableArrayList() {
    this(new ArrayList<>());
  }

  public ResizableArrayList(List<? super E> initialList) {
    list = new ArrayList<>(initialList);
  }

  public void addAll(List<? extends E> elements) {
    list.addAll(elements);
  }

  public void removeAll(List<? super E> elements) {
    list.removeAll(elements);
  }

  public List<E> getList() {
    return list;
  }

  public static void main(String[] args) {
    ResizableArrayList<Integer> numbers = new ResizableArrayList<>(
        Arrays.asList(1, 2, 3)
    );
    numbers.addAll(Arrays.asList(4, 5, 6));
    numbers.removeAll(Arrays.asList(2, 3));

    System.out.println(numbers.getList()); // [1, 4, 5, 6]
  }
}

This resizable array list can handle any typeE, allowing us to add or remove various objects to the list.

The above is the detailed content of Generic wildcards in Java functions: upper and lower bounds. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools