首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何调用具有不同泛型类型的方法

调用具有不同泛型类型的方法可以通过以下几种方式实现:

  1. 方法重载(Method Overloading):在同一个类中定义多个方法,每个方法具有不同的泛型类型参数。根据传入的参数类型,编译器会自动选择调用对应的方法。例如:
代码语言:txt
复制
public class GenericMethodExample {
    public <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }

    public <T, U> void printPair(T first, U second) {
        System.out.println("First: " + first + ", Second: " + second);
    }
}

// 调用示例
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Hello", "World"};

GenericMethodExample example = new GenericMethodExample();
example.printArray(intArray); // 调用 printArray 方法,打印整数数组
example.printArray(stringArray); // 调用 printArray 方法,打印字符串数组
example.printPair(10, "Hello"); // 调用 printPair 方法,打印整数和字符串的组合
  1. 泛型类(Generic Class):定义一个带有泛型类型参数的类,然后在创建对象时指定具体的泛型类型。通过创建不同类型的对象来调用不同泛型类型的方法。例如:
代码语言:txt
复制
public class GenericClassExample<T> {
    private T value;

    public GenericClassExample(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public void printValue() {
        System.out.println(value);
    }
}

// 调用示例
GenericClassExample<Integer> intExample = new GenericClassExample<>(10);
GenericClassExample<String> stringExample = new GenericClassExample<>("Hello");

intExample.printValue(); // 调用 printValue 方法,打印整数值
stringExample.printValue(); // 调用 printValue 方法,打印字符串值
  1. 通配符(Wildcard):使用通配符来表示不确定的泛型类型,可以调用具有不同泛型类型的方法。例如:
代码语言:txt
复制
public class WildcardExample {
    public static void printList(List<?> list) {
        for (Object element : list) {
            System.out.println(element);
        }
    }
}

// 调用示例
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
List<String> stringList = Arrays.asList("Hello", "World");

WildcardExample.printList(intList); // 调用 printList 方法,打印整数列表
WildcardExample.printList(stringList); // 调用 printList 方法,打印字符串列表

以上是调用具有不同泛型类型的方法的几种常见方式。根据具体的需求和场景,选择合适的方式来调用方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券