Java中的集合-HashSet

本文详细介绍了Java中集合类的应用,重点讲解了如何使用HashSet集合类,包括其特点、操作方法及实际应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、为什么不适用数组,而要使用集合类
1、有时候事先无法确定元素的个数
2、有时候需要存取不同类型的对象和数据
而数组只能存取相同数据类型的元素,而且长度是不可变的。

二、Java提供的集合都有哪些:
1、集(Set)
2、列表(List)
3、映射(Map)
Set介绍:不能有重复元素
HashSet类:对元素随机排序的集合类

import java.util.HashSet;
import java.util.Iterator;

public class HashSetTest{

public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
[color=red]hs.add("red");[/color]
hs.add("yellow");
hs.add("green");
[color=red]hs.add("red");[/color]
System.out.println(hs.size());
System.out.println("hs:"+hs);

Iterator it = hs.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

hs.remove("yellow");
System.out.println("removed hs:"+hs);

int is=hs.size();
System.out.println("hs size:"+is);

Object[] obj = hs.toArray();
for(int i=0; i< obj.length; i++){
System.out.println("obj["+i+"]:"+obj[i]);
}
System.out.println(hs.contains("red"));
System.out.println(hs.contains("orange"));
hs.clear();
System.out.println("cleared hs size:"+hs.size());
System.out.println(hs.isEmpty());

}
}

执行结果:
C:\javastudy>javac HashSetTest.java

C:\javastudy>java HashSetTest
[color=red]3[/color]
hs:[red, green, yellow]
red
green
yellow
removed hs:[red, green]
hs size:2
obj[0]:red
obj[1]:green
true
false
cleared hs size:0
true

C:\javastudy>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值