EffecJava Method
坚持使用Overrider注解,可以预防我们并没有重载的情况出现。
除非使用者绝对安全,不然使用保护性拷贝,可以使程序安全。
public class Period {//没有拷贝安全
private final Date start;
private final Date end;
public Period(Date start, Date end) {
if (start.compareTo(end) > 0) {
throw new IllegalArgumentException("开始时间比结束时间晚");
}
this.start = start;
this.end = end;
}
public Date getStart() {
return this.start;
}
public Date getEnd() {
return this.end;
}
}
public class PeriodProtect {
private final Date start;
private final Date end;
public PeriodProtect(Date start, Date end) {//使用了保护性拷贝,保证安全
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0) {//先拷贝后检查,是因为防止一个叫TOCTOU的一种漏洞攻击。
throw new IllegalArgumentException("开始时间比结束时间晚");
}
}
public Date getStart() {
return this.start;
}
public Date getEnd() {
return this.end;
}
}
public class Test {
public static void main(String[] args) {
Date start = new Date();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date end = new Date();
Period p = new Period(start, end);
PeriodProtect pro = new PeriodProtect(start, end);
end.setYear(88);
Date d = p.getEnd();
Date dp = pro.getEnd();
System.out.println(d);//输出 Sat Aug 20 21:04:56 CDT 1988 ,没有保护性拷贝,会根据修改end的参数被修改period里面的值,比较不安全。
System.out.println(dp);//会正确输出Sat Aug 20 21:04:56 CDT 2018,使用了拷贝安全之后就能够保证不会被篡改。
}
}
重载(Overload)和覆盖(Overrider)
public class CollectionClassfier {//测试重载Overloded,在Overloading的时候是编译时选择,所以会是选择collection
public static String classfier(List<?> list) {
return "list";
}
public static String classfier(Set<?> set) {
return "set";
}
public static String classfier(Collection<?> col) {
return "collection";
}
public static void main(String[] args) {
Collection<?>[] col = { new ArrayList<String>(), new HashMap<String, String>().values(),
new HashSet<String>() };
for (Collection<?> c : col) {
System.out.println(classfier(c));
}
/* 输出
collection
collection
collection
*/
}
}
//////////////////////////////////////////测试覆盖//////////////////////////////////
public class Wine {
String name() {
return "Wine";
}
}
public class BWine extends Wine{
@Override
String name(){
return "BWine";
}
}
public class CWine extends BWine {
@Override
String name() {
return "CWine";
}
}
public class TestForOverride {//测试覆盖
public static void main(String[] args) {
Wine[] wine = {new Wine(),new BWine(),new CWine()};
for(Wine w:wine){
System.out.println(w.name());
}
}
}
/*输出
* Wine
BWine
CWine
* */
会发现在第一个例子里面,使用的是重载,而重载是在编译时就选择好方法,在for循环中使用了Collection<?> c,所以之后执行的方法也是在选择重载的Collection,
而在覆盖中Wine w:wine,即使我们传入的是Wine,因为覆盖是在程序运行时确定,所以,可以正确识别我们需要执行的方法。
一个关于List 重载的小陷阱
public class SetList {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<Integer>();
List<Integer> list = new ArrayList<Integer>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);//这里是renmove object
list.remove(i);//这里是remove index
}
System.out.println(list + " " + set);
}
/*
*
* 输出
* [-2, 0, 2] [-3, -2, -1]
*
*
* */
}
我们想要在数组[-3,-2,-1,0,1,2]中剔除[0,1,2]这三个数值,然而set成功了list却失败了。原因是因为,在java引入了自动封装后,我们可以在set里面直接传入 int类型数值,java会自动封装成Integer类型,而list却不会,因为list的remove有两种,一种是remove(object o),一种是 remove(int index),我们传入的是int,他会执行的是remove(int index),第一次执行remove(0),剔除-3 变成[-2,-1,0,1,2],第二次remove(1),变成[-2,0,1,2],第三次remove(2)变成[-2, 0, 2] ,如果想要remove对应对象,要把int变成Integer。
EffecJava Method的更多相关文章
- jsp中出现onclick函数提示Cannot return from outside a function or method
在使用Myeclipse10部署完项目后,原先不出错的项目,会有红色的叉叉,JSP页面会提示onclick函数错误 Cannot return from outside a function or m ...
- Apply Newton Method to Find Extrema in OPEN CASCADE
Apply Newton Method to Find Extrema in OPEN CASCADE eryar@163.com Abstract. In calculus, Newton’s me ...
- 设计模式(九): 从醋溜土豆丝和清炒苦瓜中来学习"模板方法模式"(Template Method Pattern)
今天是五.四青年节,祝大家节日快乐.看着今天这标题就有食欲,夏天到了,醋溜土豆丝和清炒苦瓜适合夏天吃,好吃不上火.这两道菜大部分人都应该吃过,特别是醋溜土豆丝,作为“鲁菜”的代表作之一更是为大众所熟知 ...
- HTTP Method详细解读(`GET` `HEAD` `POST` `OPTIONS` `PUT` `DELETE` `TRACE` `CONNECT`)
前言 HTTP Method的历史: HTTP 0.9 这个版本只有GET方法 HTTP 1.0 这个版本有GET HEAD POST这三个方法 HTTP 1.1 这个版本是当前版本,包含GET HE ...
- IIS7.5上的REST服务的Put,Delete操作发生HTTP Error 405.0 - Method Not Allowed 解决方法
WebDAV 是超文本传输协议 (HTTP) 的一组扩展,为 Internet 上计算机之间的编辑和文件管理提供了标准.利用这个协议用户可以通过Web进行远程的基本文件操作,如拷贝.移动.删除等.在I ...
- The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory
The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory 这是由于项目里面的一些 ...
- Spring boot: Request method 'DELETE' not supported, Request method 'PUT' not supported, Request method 'POST' not supported
GET,POST,PUT,DELETE, Spring都支持,不要怀疑Spring, 一定是前端发送的rest 请求和后端的响应不匹配, 查找原因以及解决办法, 很简单 用chrome打开F12控制台 ...
- 异常:java.lang.LinkageError: loader constraint violation: when resolving interface method
异常:java.lang.LinkageError: loader constraint violation: when resolving interface method "javax. ...
- HTTP Method 之 Post VS. Get
引言 WebAPI 现在非常火的轻量服务框架,因其使用得使用了Http协议,并且具备了可协商内容(生成不同内容格式)等优势,所以在互联网业务中被广泛使用. 那作为HTTP最常用的两个方法Get和Pos ...
随机推荐
- 「SDOI2008」Sandy 的卡片
用第一个串建立后缀自动机.然后别的串在上面跑.从根节点开始.如果当前不能转移,一直移到slink或者根.如果移到根,能匹配长度变为0,否则变为maxlen[能转移的点]+1,再转移.转移完往slink ...
- webpack热更新
文件地址:https://pan.baidu.com/s/1kUOwFkV 从昨天下午到今天上午搞了大半天终于把热更新搞好了,之前热更新有两个问题,第一个是不能保存表单状态.第二个是更新太慢,这次主要 ...
- cmd net use
前提条件 启动服务 首先保证目标的IPC服务启动,服务为lanmanWorkstation,显示名为Workstations 端口 telnet目标计算机lanmanWorkstation服务的两个端 ...
- Being a Good Boy in Spring Festival HDU - 1850
桌子上有M堆扑克牌:每堆牌的数量分别为Ni(i=1…M):两人轮流进行:每走一步可以任意选择一堆并取走其中的任意张牌:桌子上的扑克全部取光,则游戏结束:最后一次取牌的人为胜者. 现在我们不想研究到底先 ...
- Sticks HDU - 1455 (未完成)
George took sticks of the same length and cut them randomly until all parts became at most 50 units ...
- matlab:统计矩阵中某元素的个数
三种统计方法: A=ceil(rand(,)*); a=; %第一种 sum(A(:)==a): %第二种 length(find(A==a); %第三种 logical=(A=a); sum(log ...
- 安卓——AlertDialog多样按钮
在xml 设计页面添加标签 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmln ...
- OCP-1Z0-051-V9.02-13题 单引号的使用
13. View the Exhibit and examine the structure of the PRODUCTS table. You need to generate a report ...
- Oracle Cursor用法总结
cursor分为三种,一是直接声明为cursor变量,二是首先声明类型再声明变量,三是声明为sys_refcursor. (1)直接声明 declare cursor emp_cur is sele ...
- oracle 自动备份
此次操作是每分钟备份一张表到新表(测试) 准备: 有一张表name是test 注意事项: 1.任务中调用需要显示声明权限 AUTHID CURRENT_USER 或赋予相应权限 2.单独调用过程成功, ...