public class Student {
private int score
public int getScore() {
return score
}
public void setScore(int score) {
this.score = score
}
}
实现类
import java.util.HashSet
import java.util.Set
public class AddScore {
private static Set<Student>set=new HashSet<Student>()
public static void main(String[] args) {
//创建4个student对象,将他们全部加到set集合中
Student s=new Student()
s.setScore(50)
set.add(s)
Student s2=new Student()
s2.setScore(54)
set.add(s2)
Student s3=new Student()
s3.setScore(68)
set.add(s3)
Student s4=new Student()
s4.setScore(60)
set.add(s4)
//实例化对象
AddScore add= new AddScore()
//调用方法,得山慧到总成念唯睁绩
int score=add.addScore(set)
//输出总成绩
System.out.println(score)
}
//该方法用来遍历set集合,得出总成绩
public int addScore(Set<Student>set){
int allScore=0
for (Student student : set) {
allScore+=student.getScore()
}
return allScore
}
}
public class Test {public static void main(String[] args) {
Set<高裤备Student>set=new HashSet()
set.add(new Student(1))
set.add(new Student(2))
set.add(new Student(3))
for(Student s:set){
System.out.println(s)
}
Iterator <Student>it=set.iterator()
while(it.hasNext()){
Student ss=it.next()
System.out.println(ss)
}
}
}class Student{
int number
public Student(int number) {
super()
this.number = number
}
@Override
public String toString() {
return "纯锋Student [number=" + number + "]"
}
}
注意 set无序不重复
有几个类戚毁引入不要引入awt包
/橡唤羡/*********************Studentimport java.util.Objects
public class Student {
public String name
public int age
Student(){}
Student(String name,int age){
this.name=name
this.age=age
}
public String toString(){//重写toString()
return "链段name: "+name+" age: "+age
}
public boolean equals(Object o) {//重写equals()
if (this == o) return true
if (o == null || getClass() != o.getClass()) return false
Student student = (Student) o
return age == student.age &&Objects.equals(name, student.name)
}
public int hashCode() {//重写hashCode()
return Objects.hash(name)+age
}
}
//********************StudentTest
import java.util.HashSet
public class StudentTest {
public static void main(String[] args) {
HashSet<Student>hs=new HashSet<>()
Student s1=new Student("zs",19)//s1
Student s2=new Student("zs",19)//s2
Student s3=new Student("ls"梁拍,19)//s3
hs.add(s1)//加入集合
hs.add(s2)//
hs.add(s3)//
//s1,s2,equals()返回true,s2不会加入集合
for(Student it:hs) {//遍历HasSet
System.out.println(it)
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)