[code] class test { int s; }class Shuffle1 { public static void main(String[] args) { test a=new test(),b=new test(); a.s=9; b.s=9; System.out.println(a.equals(b)); } } [/code] 哦..那这个怎么是false呀,,该怎样才能让他输出true呢??
equals 是定义在Object中的方法,java里面的类都是从object继承下来的,所以每个类都有equals方法。 每个类都可以对equals方法重写,如String中: public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
谢谢楼上几位的帮助 我这个怎么输出false呀,,怎么才让他变成true呢.. class test { int s; } class Shuffle1 { public static void main(String[] args) { test a=new test(),b=new test(); a.s=9; b.s=9; System.out.println(a.equals(b)); } }
都有,只是怎么算相当是有你自己来定,所以要按照自己的要求重写equals方法和hashCode方法
class test { int s; } class Shuffle1 { public static void main(String[] args) { test a=new test(),b=new test(); a.s=9; b.s=9; System.out.println((a.s).equals((b.s))); } } a,b是属于两个不同的对象 就象你和你朋友家的房子不一样,但是房子里都放了张一样的桌子.. 现在你比较的是房子
class test{ int s; public boolean equals(test t){ retrun s==t.s; } }
class test
{
int s;
}class Shuffle1 {
public static void main(String[] args)
{
test a=new test(),b=new test();
a.s=9;
b.s=9;
System.out.println(a.equals(b));
}
}
[/code]
哦..那这个怎么是false呀,,该怎样才能让他输出true呢??
每个类都可以对equals方法重写,如String中:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
我这个怎么输出false呀,,怎么才让他变成true呢..
class test
{
int s;
}
class Shuffle1 {
public static void main(String[] args)
{
test a=new test(),b=new test();
a.s=9;
b.s=9;
System.out.println(a.equals(b));
}
}
class test
{
int s;
}
class Shuffle1 {
public static void main(String[] args)
{
test a=new test(),b=new test();
a.s=9;
b.s=9;
System.out.println((a.s).equals((b.s)));
}
} a,b是属于两个不同的对象
就象你和你朋友家的房子不一样,但是房子里都放了张一样的桌子..
现在你比较的是房子
int s;
public boolean equals(test t){
retrun s==t.s;
}
}