java中Object.equals()简单用法
2014-07-27 21:14
483 查看
/* equals()方法默认的比较两个对象的引用! */ class Child { int num; public Child(int x){ num = x; } //人文的抛出运行时异常的好处是:可以自定义错误信息! /*public boolean equals(Object o) throws ClassCastException{ if(!(o instanceof Child)) throw new ClassCastException("中文提示:类型错误"); Child ch = (Child) o; return num == ch.num ; }*/ /* Exception in thread "main" java.lang.ClassCastException: 中文提示:类型错误 at Child.equals(PC.java:8) at PC.main(PC.java:17) */ public boolean equals(Object o){ Child ch = (Child) o; return num == ch.num ; } /* Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to Child at Child.equals(PC.java:14) at PC.main(PC.java:22) */ } public class PC{ public static void main(String[] args){ Child p1 = new Child(11); if(p1.equals(new Integer(11))) System.out.println("true"); System.out.println("这句话是否执行?");// 如果异常得到了处理, 那么这句话就会执行,否则就不会被执行! } }
相关文章推荐
- java中 equals的用法(object 和 其他类),以及与 == 的比较
- java简单数据类型用法
- Java Object equals() & hashCode()
- java Thread两种简单用法总结
- java中枚举类型enum的简单用法
- java Object equals 和 == String equals 和 == 的异同
- 2006-07-28 Java的常用包,"=="和"equals"的用法,基本数据类型与引用类型,对象的克隆
- java ObjectIn/OutStream的用法
- 【Java】简单总结一下Java中printf()的用法
- java中equals方法的用法以及==的用法
- java网络编程一:Socket用法,简单模拟一对一聊天
- 【Java】简单总结一下Java中printf()的用法
- 【Java】简单总结一下Java中printf()的用法
- Java语言深入:深入研究Java equals方法,equals,==,equals用法
- equals 与 == 的区别和用法(C# & Java)
- java equals(Object) 与 == 的区别
- JOONE(Java Object-Oriented Network Engine)使用初探(简单实例源代码)
- 集合框架----Java管理对象神奇之Object类的equals和hashcode
- java File类 简单用法举例
- 多态Object类equals方法学习笔记ObjectDemo.java