[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备份]java小题,考考你。

上一篇:[备份]关于时间和过去的一点猪头想法
下一篇:[推荐]电信用户申诉完全攻略[附申诉实例]

添加日期:2009/9/4 18:49:35 快速返回   返回列表 阅读3406次
别试,直接写答案。

===================================

Integer x = new Integer(5);
Integer y = new Integer(5);
System.out.println(x==y);
System.out.println(x==5);
System.out.println(x.equals(5));
 
Integer x = 5;
Integer y = 5;
System.out.println(x==y);
System.out.println(x.equals(y));
System.out.println(x==5);
System.out.println(x.equals(5));
 
Integer x = 5;
Integer y = new Integer(5);
System.out.println(x==y);
System.out.println(x.equals(y));
System.out.println(x==5);
System.out.println(x.equals(5));
 
String x = new String("a");
String y = new String("a");
System.out.println(x==y);
System.out.println(x=="a");
System.out.println(x.equals("a"));
 
String x="a";
String y="a";
System.out.println(x==y);
System.out.println(x=="a");
System.out.println(x.equals("a"));
 
String x="a";
String y = new String("a");
System.out.println(x==y);
System.out.println(x=="a");
System.out.println(x.equals("a"));
=========================================

Integer的我再试试。

-----------------------------

String对象不可变,所以

String x="5";

String y="5";

y其实与x的指向一样,都是同一个对象。

如果使用new String("5"),那么每次都是一个新的对象。

----------------------------

==始终比较(是否指向同一个对象)

Object的equals,也是比较指向的,

但String覆盖了该方法,比较内容了。

----------------------------------

综合以上几点,String的题应该没问题了。

 

翻了书,终于搞明白了,哈哈。

=============================

Integer的equals也重写了,比较值了。

(1)

Integer x = new Integer(5);
Integer y = new Integer(5);
System.out.println(x==y);
System.out.println(x==5);
System.out.println(x.equals(5));

这个,没啥说的,x和y都是new出来的,是两个对象,答案是false,true,true.

判断x==5时,将Integer对象拆包,值为5,与5相等,所以为true.

(2)

Integer x = 5;
Integer y = 5;
System.out.println(x==y);
System.out.println(x.equals(y));
System.out.println(x==5);
System.out.println(x.equals(5));

Integer x=5这样声明时,自动将5打包为Integer对象。

按理来说,x和y应该打包为两个对象,但是,打包规范要求:

boolean,byte,char<=127,-128-127之间的short和int,要打包到固定的对象中。
所以,这里x和y是同一个对象,所以答案是:true,true,true,true。

如果将5都换成128,那么答案将是:false,true,true,true。

(3)

Integer x = 5;
Integer y = new Integer(5);
System.out.println(x==y);
System.out.println(x.equals(y));
System.out.println(x==5);
System.out.println(x.equals(5));

这个,y是new出来的,自然和x是不同的对象。

答案:false,true,true,true。

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved