java HashSet的使用

本文介绍 Java 中 HashSet 的基本用法,包括添加元素、检查元素是否存在、删除元素等操作,并通过示例代码展示了 HashSet 的典型应用场景。

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

日志 > 软件编程
设置置顶 | 编辑 | 删除

java HashSet的使用

发表于:2008年5月3日 16时57分31秒阅读(3)评论(0) 本文链接:http://user.qzone.qq.com/169188811/blog/1209805051
java HashSet的使用
import [url=javascript:;] java [/url].util.HashSet;
import java.util.Iterator;
public class WpsklHashSet
{
//java 中Set的使用(不允许有重复的对象):
public static void main(String[] args)
{
  HashSet hashSet=new HashSet();
  String a=new String("A");
  String b=new String("B");
  String c=new String("B");
  hashSet.add(a);
  hashSet.add(b);
  System.out.println(hashSet.size());
  String cz=hashSet.add(c)?"此对象不存在":"已经存在";
  System.out.println("测试是否可以添加对象    "+cz);
  System.out.println(hashSet.isEmpty());
  //测试其中是否已经包含某个对象
  System.out.println(hashSet.contains("A"));
  Iterator ir=hashSet.iterator();
  while(ir.hasNext())
  {
   System.out.println(ir.next());
  }
  //测试某个对象是否可以删除
  System.out.println(hashSet.remove("a"));
  System.out.println(hashSet.remove("A"));
  //经过测试,如果你想再次使用ir变量,必须重新更新以下
  ir=hashSet.iterator();
  while(ir.hasNext())
  {
   System.out.println(ir.next());
  }

}
}
  

 
请选择道具
温馨提示:点击验证码输入框,以获取验证码
请输入验证码:
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值