Java+包裹类型_自己实现的Java装箱类,可以包裹任意类型

package generic;

// https://docs.oracle.com/javase/tutorial/java/generics/types.html

/*

* A Simple Box Class

Begin by examining a non-generic Box class that operates on objects of any type.

It needs only to provide two methods: set, which adds an object to the box, and get, which retrieves it:

public class Box {

private Object object;

public void set(Object object) { this.object = object; }

public Object get() { return object; }

}

Since its methods accept or return an Object, you are free to pass in whatever you want,

provided that it is not one of the primitive types. There is no way to verify,

at compile time, how the class is used. One part of the code may place an Integer in the box and

expect to get Integers out of it, while another part of the code may mistakenly pass in a String,

resulting in a runtime error.

*/

public class Box {

// T stands for "Type"

private T t;

public void set(T t) {

this.t = t;

System.out.println("Set called: " + t);

}

public T get() {

System.out.println("Get called: " + t);

return t;

}

/*

* Box integerBox;

* Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will

* hold a reference to a "Box of Integer", which is

* how Box is read.

*/

static public void main(String[] arg){

Box integerBox = new Box();

integerBox.set(1);

System.out.println("value: " + integerBox.get());

Box stringBox = new Box();

stringBox.set("Jerry");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值