编写一个自定义类:Student,包含两个成员变量( private String name; //姓名 private int score; //总分 ); 2.编写一个测试程序,分别在HashSet和TreeSet容器对象添加四个Student类对象元素,要求: (1)HashSet和TreeSet容器中定不能不能存放相同内容的对象(即对象的name和score各自的值相等时,视为相同的元素); (2)元素之间比较大小时 ,先按name值比较,再按score值比较。 (3)遍历两个容器中的各个元素,显示在屏幕上。
时间: 2023-05-26 13:07:50 浏览: 93
public class Student implements Comparable<Student>{
private String name; //姓名
private int score; //总分
public Student(String name, int score){
this.name = name;
this.score = score;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public void setName(String name){
this.name = name;
}
public void setScore(int score){
this.score = score;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Student){
Student other = (Student) obj;
return this.name.equals(other.getName()) && this.score == other.getScore();
}
return false;
}
@Override
public int hashCode(){
return name.hashCode() + score;
}
@Override
public int compareTo(Student other){
int result = name.compareTo(other.getName());
if(result == 0){
result = score - other.getScore();
}
return result;
}
@Override
public String toString(){
return "Student [name=" + name + ", score=" + score + "]";
}
}
import java.util.*;
public class Test{
public static void main(String[] args){
Set<Student> set1 = new HashSet<>();
Set<Student> set2 = new TreeSet<>();
set1.add(new Student("Tom", 80));
set1.add(new Student("Bob", 90));
set1.add(new Student("Tom", 70));
set1.add(new Student("Kate", 85));
set2.add(new Student("Tom", 80));
set2.add(new Student("Bob", 90));
set2.add(new Student("Tom", 70));
set2.add(new Student("Kate", 85));
System.out.println("HashSet:");
for(Student s : set1){
System.out.println(s);
}
System.out.println("TreeSet:");
for(Student s : set2){
System.out.println(s);
}
}
}
阅读全文