黑马程序员技术交流社区
标题:
java中hashset的用法
[打印本页]
作者:
liuning
时间:
2015-6-1 11:20
标题:
java中hashset的用法
package setSetDemo;
import java.util.HashSet;
import java.util.Set;
/**
* 本程序创建了两个规则集set1和set2,完成了向set中加入元素(String)
* 和删除元素的操作
* 并且实现了addAll(set)的操作等
* */
public class TestMethodInCollection {
public static void main(String[] args){
//Create set1
Set<String> set1 = new HashSet<String>();//Create a hash set
//Add Strings to the hashSet
set1.add("London");
set1.add("Paris");
set1.add("New York");
set1.add("San Francisco");
set1.add("Beijing");
System.out.println("set1 is "+set1);
System.out.println(set1.size() + " elements in set1");
//Delete a string from set1
set1.remove("London");
//打印出set1这个字符串集合
System.out.println("\nset1 is " + set1);
// 打印出set1元素的个数
System.out.println(set1.size() + " elements in set1");
//Create set2
Set<String> set2 = new HashSet<String>();
set2.add("Shanghai");
set2.add("London");
set2.add("Paris");
System.out.println("set2 is " + set2);
System.out.println(set2.size()+"elements in set2");
//contains包含 set2 contans Taipei this element 返回类型是Boolean类型
System.out.println("\nIs Taipei in set2 ? " + set2.contains("Taipei"));
//All the elements in the set2 added to set1
set1.addAll(set2);
//Display set1
System.out.println("\nAfter adding set2 to set1 ,set1 is " + set1);
//Deleted from the set1 of set2 elements
set1.removeAll(set2);
System.out.println("\nAfter removing set2 from set1, set1 is " + set1);
set1.retainAll(set2);
//保留set1 和set2 里共有的元素 为null
System.out.println("After removing common elements in set2 " + "from set1, set1 is " + set1);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2