首页 > 代码库 > hashcode和equals方法
hashcode和equals方法
分析:
1:Person类
1:姓名和年龄
2:重写hashCode和equals方法
1:如果不重写,调用Object类的equals方法,判断内存地址,为false
1:如果是Person类对象,并且姓名和年龄相同就返回true
2:如果不重写,调用父类hashCode方法
1:如果equals方法相同,那么hashCode也要相同,需要重写hashCode方法
3:重写toString方法
1:不重写,直接调用Object类的toString方法,打印该对象的内存地址
Person类
class Person { private String name; private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name; this.age = age; }
@Override public int hashCode() { return this.name.hashCode() + age; }
@Override public boolean equals(Object obj) { if (!(obj instanceof Person)) { return false; } Person p = (Person) obj; return this.name.equals(p.name) && this.age == p.age; }
@Override public String toString() { return "Person :name=" + name + ", age=" + age; }
}
|
public static void main(String[] args) { Person p1 = new Person("张三", 19); Person p2 = new Person("李四", 20); Person p3 = new Person("王五", 18); Collection list = new ArrayList(); list.add(p1); list.add(p2); list.add(p3); // isEmpty() 判断集合是否为空 boolean empty = list.isEmpty(); System.out.println(empty); // 返回集合容器的大小 int size = list.size(); System.out.println(size); // contains()判断集合何中是否包含指定对象 boolean contains = list.contains(p1); System.out.println(contains);
// remove(); 将指定的对象从集合中删除 list.remove(p1);
// clear() 清空集合中的所有元素 list.clear(); System.out.println(list);
}
|
//使用集合存储自定义对象2 class Book { private String name; private double price;
public Book() {
}
public Book(String name, double price) { this.name = name; this.price = price; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override public int hashCode() { return (int) (this.name.hashCode() + price); }
@Override public boolean equals(Object obj) { if (!(obj instanceof Book)) { return false; } Book book = (Book) obj; return this.name.equals(book.name) && this.price == book.price; }
@Override public String toString() { return "book:@ name:" + this.name + ", price:" + this.price; } } public class Demo1 { public static void main(String[] args) { Collection col = new ArrayList(); col.add(new Book("think in java", 100)); col.add(new Book("core java", 200)); System.out.println(col); } } |
hashcode和equals方法