首页 新闻 赞助 找找看

==与equal问题,编译不通过是怎么回事?

0
悬赏园豆:10 [已解决问题] 解决于 2013-08-01 21:03

public class Test {
        public static void main(String[] args) {
                String s = new String("ABC");
                System.out.println(s);
                Integer x = new Integer(2);
                
                System.out.println(x.equals(s));
                System.out.println(x == s);
        }

}
System.out.println(x.equals(s));
这句可以运行
System.out.println(x == s);
这句在编译时就无法通过,

这是什么原因?

zhangpengpeng的主页 zhangpengpeng | 初学一级 | 园豆:114
提问于:2013-07-24 10:33
< >
分享
最佳答案
0


// 返回结果:
// 如果 obj 是 System.Int32 的实例并且等于此实例的值,则为 true;否则为 false。
public override bool Equals(object obj);

对于预定义的值类型,如果操作数的值相等,则相等运算符 (==) 返回 true,否则返回 false。 对于 string 以外的引用类型,如果两个操作数引用同一个对象,则 == 返回 true 对于 string 类型,== 比较字符串的值。

收获园豆:10
steve min | 菜鸟二级 |园豆:234 | 2013-07-24 21:26
其他回答(7)
0

这是基本的类型转换问题哦

坤坤 | 园豆:919 (小虾三级) | 2013-07-24 10:38
0

类型不一致,不能相等;

equals方法有很多重载,所以可以通过编译;

幻天芒 | 园豆:37175 (高人七级) | 2013-07-24 10:58
0

类型不一致

panjk | 园豆:712 (小虾三级) | 2013-07-24 11:37
0

InRole = roleid.Contains(user.UserID) ? true : false

用这种形式了?Contains

真假不分 | 园豆:248 (菜鸟二级) | 2013-07-26 01:31
2

这个问题是因为类型不一致造成的,Integer 是int的包装类型,是Object(对象)类型,而String即不是基本类型,也不是引用类型,它是一个特殊的final类对象,让String类型和对象类型做比较,就好比:周长和面积比较大小,没有可比性!如果想解决这个问题,就得保证类型一致。

补充一句:“== ”是比较地址,“equal “是比较值!!!

希望对你有用。

狂奔的程序猿 | 园豆:244 (菜鸟二级) | 2013-07-27 11:03
0

你首先要知道的是,equal()方法和==之间的区别,他们是什么使用,equal()方法比较的是你输入的两个值得长得像不像,比较的是值是不是一样。==比较的是地址,你要知道的是比较的两者是不是一样的类型,如果类型不一样,他们的地址肯定不一样。

侯志凯 | 园豆:202 (菜鸟二级) | 2013-07-30 17:29
0

/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

此为IntegerJDK源码 如果这都解释不了你编译不通过的原因 那也没什么好说的了 应该加强基础知识的学习了

zm112358 | 园豆:213 (菜鸟二级) | 2013-08-01 18:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册