Java---包装类与泛型
    		       		warning:
    		            这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
    		        
        		                
                
// 定义一个泛型类
class Box<T> {
    private T t;
 
    public Box(T t) {
        this.t = t;
    }
 
    public T get() {
        return t;
    }
 
    public void set(T t) {
        this.t = t;
    }
}
 
public class Main {
    public static void main(String[] args) {
        // 创建Integer类型的Box对象
        Box<Integer> integerBox = new Box<>(10);
        System.out.println("整数包装类: " + integerBox.get());
 
        // 创建String类型的Box对象
        Box<String> stringBox = new Box<>("Hello World");
        System.out.println("字符串包装类: " + stringBox.get());
    }
}这段代码定义了一个泛型类Box,它可以持有任何类型的对象。在main方法中,我们创建了两个Box实例,一个持有Integer类型的值,另一个持有String类型的值,并打印出它们的值。这展示了泛型在Java中的应用,它允许我们以灵活的方式使用类型。
评论已关闭