声明一个set集合,使用HashSet类,来保存十个字符串信息,然后通过这个集合,然后使用iterator()方法,得到一个迭代器,遍历所有的集合中所有的字符串;然后拿出所有的字符串拼接到一个StringBuffer对象中,然后输出它的长度和具体内容; 验证集合的remove()、size()、contains()、isEmpty()等

 1 package com.lanxi.demo1_3;
 2 import java.util.HashSet;
 3 import java.util.Iterator;
 4 import java.util.Set;
 5 public class TestHash {
 6     public static void main(String[] args) {
 7         Set hash=new HashSet();
 8         hash.add("明");
 9         hash.add("天");
10         hash.add("最");
11         hash.add("好");
12         hash.add("的");
13         hash.add("准");
14         hash.add("备");
15         hash.add("是");
16         System.out.print("集合中的字符串信息为:");
17         Iterator it=hash.iterator();
18         while(it.hasNext()){
19             System.out.print(it.next());
20         }
21         System.out.println();
22         StringBuffer buf=new StringBuffer();
23         buf.append(hash);
24         System.out.println("buf里的内容为:"+buf);
25         System.out.println("buf长度为:"+buf.length());
26         System.out.println("从集合中删除“是”:"+hash.remove("是"));
27         System.out.println("集合长度:"+hash.size());
28         System.out.println("集合中是否包含“是”:"+hash.contains("是"));
29         System.out.println("集合是否为空:"+hash.isEmpty());
30         
31     }
32 
33 }

运行结果

原文地址:https://www.cnblogs.com/www-x/p/8626489.html