<span style="font-family: 'Microsoft YaHei'; line-height: 29.7px; white-space: pre-wrap; background-color: rgb(255, 255, 255);">1.关系操作符中==与equals( )的比较</span>
<span style="font-family: 'Microsoft YaHei'; line-height: 29.7px; white-space: pre-wrap; background-color: rgb(255, 255, 255);">1.关系操作符中==与equals( )的比较</span>
<span style="font-family:Times New Roman;font-size:10px;">public class Equivalence {
public static void main(String[] args){
Integer n1=new Integer(47);
Integer n2=new Integer(47);
System.out.println(n1==n2);//比较对象引用
System.out.println(n1.equals(n2));//比较对象的内容
}
}</span>
后台输出:false true
针对基本数据类型equals()比较的是对象的实际内容,==比较的是对象的引用。但是针对自己新创建的类,equals( )默认比较引用,需要覆盖equals( )方法才能,满足对内容的比较。
2.boolean类型的注意事项
<span style="font-family:Times New Roman;">//Treating an int as a boolean is not legal Java:
//print("i && j is "+(i&&j))
//print("i || j is "+(i||j))
print("!i is "+!i)</span>不可以将非布尔类型的值当做布尔值在逻辑表达式中使用。3.模拟扔硬币的结果
<span style="font-family:Times New Roman;font-size:10px;">import java.util.Random;
public class Coin {
public static void main(String[] args){
Random rand=new Random();
int x=0;
int y=0;
for(int i=0;i<100000;i++){
int j=rand.nextInt(2);
if(j==1)
x++;
else
y++;
}
System.out.println("x:"+x);
System.out.println("y:"+y);
System.out.println("x/(y+x):"+(float)x/(y+x));
}
}</span>
本文对比了Java中==与equals()的区别,详细解释了二者在对象引用与内容比较上的不同,并给出了boolean类型的使用注意事项。此外,还提供了一个模拟扔硬币结果的示例程序。

被折叠的 条评论
为什么被折叠?



