HashSet和TreeSet

This commit is contained in:
seahi 2024-12-01 22:36:03 +08:00
parent d1ec1423dd
commit 5a4df5e6f3
10 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,73 @@
package chapter6;
import java.util.HashSet;
import java.util.Iterator;
class Student implements Comparable<Student> {
String id;
String name;
int height;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public void setHeight(int height) {
this.height = height;
}
public String toString() {
return id + ":" + name;
}
public int hashCode() {
return id.hashCode();
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return this.id.equals(other.id);
}
public int compareTo(Student other) {
if (this.height > other.height) {
return 1; // 返回正数表示""""
} else if (this.height < other.height) {
return -1; // 返回负数表示""""
} else {
return 0; // 返回0表示""""一样大
}
}
}
public class Example08 {
public static void main(String[] args) {
HashSet<Student> students = new HashSet<>();
Student s1 = new Student("1", "张三");
Student s2 = new Student("2", "李四");
Student s3 = new Student("2", "李四");
Student s4 = new Student("3", "王五");
students.add(s3);
students.add(s4);
students.add(s1);
students.add(s2);
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student);
}
}
}

View File

@ -0,0 +1,21 @@
package chapter6;
import java.util.TreeSet;
public class Example12 {
public static void main(String[] args) {
Student s1 = new Student("1", "张三");
s1.setHeight(175);
Student s2 = new Student("2", "李四");
s2.setHeight(170);
Student s4 = new Student("3", "王五");
s4.setHeight(180);
TreeSet<Student> students = new TreeSet<>();
students.add(s1);
students.add(s2);
students.add(s4);
System.out.println(students);
}
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example14 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example15 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example19 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example21 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example22 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example23 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example24 {
}

View File

@ -0,0 +1,4 @@
package chapter6;
public class Example25 {
}