- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- private String value = null;
- public Test(String v) {
- value = v;
- }
- public boolean equals(Test o){//参数为Test
- if(o==this) return true;
- if(o instanceof Test) {
- Test t = (Test) o;
- return this.value.equals(t.value);
- }
- return false;
- }
- public static void main(String[] args) {
- List list = new ArrayList();
- Test test1 = new Test("Object");
- Test test2 = new Test("Object");
- Test test3 = new Test("Object");
- Object test4 = new Test("Object");
- list.add(test1);
- System.out.println(list.contains(test2));
- System.out.println(test2.equals(test3));
- System.out.println(test3.equals(test4));
- }
- }
输出:false
true
false
- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- private String value = null;
- public Test(String v) {
- value = v;
- }
- public boolean equals(Object o){//参数为Object
- if(o==this) return true;
- if(o instanceof Test) {
- Test t = (Test) o;
- return this.value.equals(t.value);
- }
- return false;
- }
- public static void main(String[] args) {
- List list = new ArrayList();
- Test test1 = new Test("Object");
- Test test2 = new Test("Object");
- Test test3 = new Test("Object");
- Object test4 = new Test("Object");
- list.add(test1);
- System.out.println(list.contains(test2));
- System.out.println(test2.equals(test3));
- System.out.println(test3.equals(test4));
- }
- }
输出为:true
true
true