前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自己实现的Java装箱类,可以包裹任意类型

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

作者头像
Jerry Wang
发布2020-04-28 15:30:18
4900
发布2020-04-28 15:30:18
举报
代码语言:javascript
复制
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> {
	// 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<Integer> 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<Integer> is read.
     */
    static public void main(String[] arg){
    	Box<Integer> integerBox = new Box<Integer>();
    	integerBox.set(1);
    	System.out.println("value: " + integerBox.get());
    	
    	Box<String> stringBox = new Box<String>();
    	stringBox.set("Jerry");
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档