标题:java集合判断对象相等和比较大小的方法
- 判断Java集合对象相同:
(1)判断equals是否返回true;
(2)判断hascode是否相等;
package edu.xalead;
import java.util.HashSet;
public class Test {
/**
* 相同的哈希码,对象相同
*/
public static void main(String[] args) {
HashSet q = new HashSet();
q.add("hello");
q.add("hello");
q.add("hello");
System.out.println(q.size());
q = new HashSet();
q.add(13);
q.add(13);
q.add(13);
System.out.println(q.size());
q = new HashSet();
q.add(new Student("KAAK",143536,'女'));
q.add(new Student("KAAK",143536,'女'));
q.add(new Student("KAAK",143536,'女'));
System.out.println(q.size());
HashSet w = new HashSet();
w.add(new Student1("jiaja",143536,'男'));
w.add(new Student1("jiaja",143536,'男'));
w.add(new Student1("jiaja",143536,'男'));
System.out.println(w);
System.out.println(w.size());
}
// c = new HashSet();
// c.add(new Student(222,"旺达"));
// c.add(new Student(222,"旺达"));
// c.add(new Student(222,"旺达"));
// System.out.println(c.size())
}
在Student1未继承Object或未实现接口Comparable时,w.size=3,因为每new一次Student1对象,地址不同.
测试结果&