自己实现的Java装箱类,可以包裹任意类型
JAVA 实现 类型 可以 自己 任意 装箱 包裹
2023-09-14 09:03:08 时间
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");
}
}
相关文章
- java分层打印二叉树_基于Java的二叉树层序遍历打印实现
- java中Set集合的遍历及实现类比较分析
- java数组定义长度_JAVA数组的定义
- MySQL字段类型如何转为java_Java JDBC中,MySQL字段类型到JAVA类型的转换
- java平均的随机数_Java 随机数详解「建议收藏」
- java中map根据value找key_Java Map和Map<String, Object>类型,map通过value找key
- 【说站】java枚举如何实现单例
- JAVA对象转map_java处理字符串类型的map
- java事务_Java 事务详解[通俗易懂]
- java 舆情分析_基于Java实现网络舆情分析系统研究与实现.doc[通俗易懂]
- Spring Boot | 集成MapStruct实现不同类型Java对象间的自动转换
- Java生成随机无重复随机数,使用ArrayList实现详解编程语言
- Java操作MySQL数据库:实现看似不可能的梦想(java连接mysql数据库)
- 服务器实现Java远程访问Linux服务器(java远程linux)
- 自动清除处理 Redis Java 中过期自动键值清理策略(redisjava过期)
- 机制Java Redis实现自动过期机制(redisjava过期)
- 控制基于Redis与Java实现缓存过期控制(redisjava过期)
- MySQL与Java的结合:实现强大的数据持久化功能(mysql与java)
- 策略使用Java实现Redis过期策略(redisjava过期)
- 策略实现基于Redis与Java的有效过期策略(redisjava过期)
- 机制使用 Java 和 Redis 实现复杂数据过期机制(redisjava过期)
- Java编程实现MySQL表备份(java备份mysql表)
- 使用Java连接SQL Server数据库,轻松实现数据交互(java连sqlserver)
- 使用Java实现MySQL数据恢复操作(java恢复mysql)
- 在Linux上实现Java程序的运行(linux运行java程序)
- 使用Java语言写Redis实现一个分布式缓存系统(用java写个redis)
- Java迭代Oracle实现数据库更高性能(java迭代oracle)
- Oracle中实现Java程序设计的极限可能性(oracle中的java)
- Java实现Redis队列锁功能(redis队列锁java)
- Java注册邮箱激活验证实现代码