HashSet经典面试题记录
2022-12-29 11:30 投稿人:网络编辑
首先有个person类实现了Comparable接口
class Person implements Comparable{ String name; int age; public Person(String name1, int age){ name = name1; this.age = age; } @Override public boolean equals(Object o) { System.out.println("equals-----------------------"); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && name.equals(person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { System.out.println("compare to -------------"); if (o instanceof Person){ Person o1 = (Person) o; return Integer.compare(this.age,o1.age); } throw new RuntimeException("输入类型不符合"); } }re>
以下是测试的代码re>@Test
public void test3(){
HashSet