HashSet是Java中常用的Set集合,向HashSet集合中添加數(shù)據(jù)對象時,首先會調(diào)用對象的hashCode()方法獲取哈希碼,根據(jù)哈希碼計算對象的存儲位置,如果相應(yīng)位置上已經(jīng)有數(shù)據(jù)對象,則會調(diào)用對象的equals()方法判斷新加入的對象與現(xiàn)有對象是否重復(fù),如果重復(fù)則拒絕加入。為了使用HashSet集合正確存儲自定義類的對象,自定義類需要重寫equals()方法和hashCode()方法。
編寫程序完成以下功能:定義一個學(xué)生類Student,屬性包括String類型的id、name和int類型的age(id屬性字符串內(nèi)容相同的則認為是同一個學(xué)生),為三個屬性定義get和set方法。重寫equals()方法和hashCode()方法,使得當使用HashSet存儲Student類的對象時,id重復(fù)的學(xué)生對象不能重復(fù)添加到集合。輸入4個學(xué)生類對象的屬性值,創(chuàng)建4個Student類對象,將其添加到一個HashSet<Student>集合,遍歷集合,輸出集合中各個學(xué)生的信息。
輸入說明:輸入4個Student類對象的屬性值,每個對象屬性值按一行輸入,以空格分割。
輸出說明:集合中存儲的Student類對象的信息,每個對象信息占一行,輸出格式為 id:name:age。
輸入樣例1:
2022001 Tom 19
2022002 Jerry 18
2022003 Eason 20
2022002 Jerry 18
輸入樣例2:
2022001 Tom 19
2022002 Jerry 18
2022003 Eason 20
2022004 Jerry 18
輸出樣例1:
2022001:Tom:19歲
2022002:Jerry:18歲
2022003:Eason:20歲
輸出樣例2:
2022001:Tom:19歲
2022002:Jerry:18歲
2022003:Eason:20歲
2022004:Jerry:18歲文章來源:http://www.zghlxwxcb.cn/news/detail-714029.html
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
List<String []> list = new ArrayList<>();
HashSet<Student> hs= new HashSet<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
String str = scanner.nextLine();
list.add(str.split(" "));
}
//遍歷集合
for (String[] strings : list) {
Student s1 = new Student();
s1.setId(strings[0]);
s1.setName(strings[1]);
s1.setAge(Integer.parseInt(strings[2]));
hs.add(s1);
}
for (Student h : hs) {
System.out.println(h.getId() + ":" + h.getName() + ":" + h.getAge() + "歲");
}
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-714029.html
到了這里,關(guān)于Java練習(xí)題2022-1的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!