看个泛型的例子

package com.wjy.effective;

public class FStyle {
    public <E> E getField(E param){
        E result=param;
        return result;
    }
}

 

客户端程序:

package com.wjy.effective;

public class TestFStyle {
    public static void main(String args[]){
        FStyle fStyle=new FStyle();
//        int n=fStyle.getField(1)+2;
        String s=fStyle.getField("hello")+2;
        
//        System.out.println("result is; "+n);
        System.out.println("result is; "+s);
    }
}

 

运行结果:

//result is3
result is; hello2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,这个问题很好,这是一个Java全面泛型例子: ```java public class GenericExample<T> { private T data; public GenericExample(T data) { this.data = data; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static void main(String[] args) { // Example 1: Using generic class with Integer type parameter GenericExample<Integer> integerExample = new GenericExample<>(10); System.out.println("Data in integerExample: " + integerExample.getData()); // Example 2: Using generic class with String type parameter GenericExample<String> stringExample = new GenericExample<>("Hello, world!"); System.out.println("Data in stringExample: " + stringExample.getData()); // Example 3: Using generic method to print array of any type Integer[] intArray = {1, 2, 3, 4, 5}; String[] stringArray = {"a", "b", "c", "d", "e"}; printArray(intArray); printArray(stringArray); } public static <E> void printArray(E[] elements) { for (E element : elements) { System.out.print(element + " "); } System.out.println(); } } ``` 在这个例子,我们定义了一个泛型类`GenericExample<T>`,它有一个类型参数`T`,代表这个类可以接受任何类型的数据。我们在构造函数传入一个类型为`T`的数据,然后使用`getData()`方法获取这个数据。我们还定义了一个`setData()`方法,可以用来更新这个数据。 在`main()`方法,我们创建了两个`GenericExample`对象,一个使用`Integer`类型参数,另一个使用`String`类型参数,以便演示该类可以接受任何类型的数据。我们还定义了一个泛型方法`printArray(E[] elements)`,该方法可以打印任何类型的数组,包括`Integer`和`String`类型数组。在`main()`方法,我们演示了如何使用该方法打印`Integer`和`String`类型的数组。 希望这个例子能够回答您的问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值