码讲——JavaBean与Object
2015-06-30 21:37
453 查看
<pre name="code" class="java">//====================JavaBean====================== class Point implements Comparable<Point>,Serializable{ private static final long LEVEL = 20150701;//本码讲版本 /* * 版本号 * 如不加,序列化的时候会自动生成,这种方式严格的控制兼容性,只要类发生改变 * 则版本号就会改变,反序列化失败 * 如果明确指定版本号,当类发生改变但版本号相同时,则会使用兼容模式,求同存异 * 原来对象有的属性,现在还有的就还原 * 原来对象有的属性,现在没有的就忽略 * 原来对象没有的属性,现在有的则使用默认值 */ private static final long serialVersionUID = 1L; //关键字:transient 声明了该关键字的属性将不会被序列化 private transient int x; private int y; public Point(){ this(0,0); } public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } /* * * hashcode()方法有以下注意事项:(hashcode的用于散列表数据结构计算存放位置) * 1、若一个类重写了equals方法,那么就应当重写hashcode()方法。 * 2、若两个对象的equals方法比较为true,那么它们应当具有相同的hashcode值。 * 3、对于同一个对象而言,在内容没有发生改变的情况下,多次调用hashCode()方法应当总是返回相同的值。 * 4、对于两个对象equals比较为false的,并不要求其hashcode值一定不同,但是应尽量保证不同,这样可以提高散列表性能。 */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { // 重写equals方法准则见文档: // 1、自反性 2、对称性xy yx 3、传递性xy yz xz 4、一致性参数不变时多次调用应一致 if (obj == null) { return false; } if (this == obj) {// 自反性 return true; } if (obj instanceof Point) { Point point = (Point) obj; return point.x == this.x && point.y == this.y; } else return false; } @Override public String toString() { return "(" + x + "," + y + ")"; } // 返回值负整数、零或正整数,根据此对象是小于、等于还是大于指定对象 @Override public int compareTo(Point point) { int l1 = YaoUtils.sqrtInt(this.getX(), 2) + YaoUtils.sqrtInt(this.getY(), 2); int l2 = YaoUtils.sqrtInt(point.getX(), 2) + YaoUtils.sqrtInt(point.getY(), 2); return l1 - l2; } //@Test public void prinPoint() { // test toString() Point point = new Point(1, 2); System.out.println(point); } //@Test public void testEquals() { Point point = new Point(1, 2); Point point1 = new Point(1, 3); System.out.println(point.equals(point1)); } }
相关文章推荐
- OC基础2:一些基本概念
- GitHub Top Users Objective-C World
- “Core Data could not fulfill a fault” for objects that were not deleted
- Objective-C 内存管理之 _ARC
- C#取硬盘、CPU、主板、网卡的序号 ManagementObjectSearcher
- block的实现原理
- [Objective-C]SEL类型、@selector选择器
- 面向对象 object 内部类
- [object-c]格式化时间
- JSONObject与JSONArray的使用
- objective-c类初始化
- Coroutine couldn't be started because the the game object 'GameController' is inactive!
- Understanding the Objective-C Runtime
- Github上优秀的Objective-C项目简介
- php分析MSSQL返回的时间位object,怎样输出时间?
- Could not reserve enough space for object heap 问题解决
- Github上优秀的Objective-C项目简介
- org.tinygroup.context2object-参数对象构建
- JavaSE实战——API(上) Eclipse使用、Object、Scanner、String、StringBuffer、StringBuilder、Integer、模拟用户登录案例
- 15 面向对象 抽象类 内部类 Object类