HashSet類,是存在於java.util包中的類 。同時也被稱為集合,該容器中只能存儲不重復的對象。底層是由HashMap來存儲的,因為HashSet不能重復,你知道HashMap的鍵不能重復就明白了這一個原理了,所以對於HashMap很熟悉的話對於HashSet就能夠很快的知道底層實現。
HashSet是set接口的實現類,也是我們最常用的set集合
儲存的是無序,唯一的對象。遍歷可能是有序,可能是無序的
由於是無序的所以每組數據都沒有索引,很多list可用的方法他都沒有
凡是需要通過索引來進行操作的方法都沒有,所以也不能使用普通for循環來進行遍歷,只有加強型for和迭代器兩種遍歷方法
HashSet的元素不能重復
HashSet中允許有NULL值
例如:
get(i);
set(int index,Object o);
remove(int index);
等需要用索引來操作的方法都沒有;
HashSet的各種方法:
1.增加
add(null);
2.刪除
remove(news);
3.對比查找
contains(news);
4.清空集合
clear();
5.獲取長度
size();
HashSet遍歷
迭代遍歷
Set<String> set = new HashSet<String>();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
for循環遍歷
for (String str : set) {
System.out.println(str);
}
使用示例:
public class NewsHashSet {
public static void main(String[] args) {
News news = new News(1, "北京終於放晴了!", "新聞社");
News news2 = new News(2, "香港回歸紀念日", "人民新聞");
News news3 = new News(3, "假奶粉事件曝光", "人民新聞網");
//創建HashSet集合,儲存無序,唯一的數據
//HashSet是是使用equals來進行對象對比,確定數據是唯一的
//如果兩個數據的對象是一致的,那么HashSet將會把這兩個合並,只儲存一個空間
HashSet<News> set = new HashSet<News>();
set.add(news);
set.add(news2);
set.add(news3);
//由於HashSet儲存數據都是無序的,所以不能用get(i);來獲取具體對象
//所以我們必須通過遍歷來得到HashSet的各個數據,由於是沒有索引的
//所以不能使用普通類型的for來遍歷它
//HashSet只能通過增強型for和迭代器來遍歷它
//增強型for
for(News n : set){
System.out.println(n.getID()+"\t"+n.getLitter()+"\t"+n.getAuthor());
}
System.out.println("*****************************************");
//迭代器
Iterator<News> it = set.iterator();
while (it.hasNext()) {
News n = it.next();
System.out.println(n.getID()+"\t"+n.getLitter()+"\t"+n.getAuthor());
}
//set的各種方法
//set增加
set.add(null);
//刪除
set.remove(news);
//對比查找
set.contains(news);
//清空集合
set.clear();
//獲取長度
set.size();
}
}
---------------------
作者:Linias
來源:CSDN
原文:https://blog.csdn.net/qq_29373285/article/details/84940885
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!