Java的HashSet

HashSet是一个集合数据类型,可以装入多个不重复的数据

/**
 * @author liu-xiao-ge
 *
 */
public class HashSetDemo
{

	public static void main(String[] args)
	{
		HashSet<String> set1 = new HashSet<>();
		set1.add("郭靖");
		set1.add("黄蓉");
		set1.add("洪七公");
		set1.add("黄药师");
		set1.add("杨过");
		
		//获取set的长度
		int size = set1.size();
		System.out.println(size);
		
		//移除元素
		set1.remove("马蓉");
		
		//遍历set集合(方法一)
		Iterator<String> iter = set1.iterator();
		while(iter.hasNext()){
			String next = iter.next();
			System.out.println(next);
		}
		
		//遍历set集合(方法2)--增强for循环
		for(String temp:set1){
			System.out.println(temp);
		}
		
		//遍历数组也可以用这个方法
		int[] arr = new int[] {4,5,7,8,9};
		for(int i:arr){
			System.out.println(i);
		}
		
		
		//遍历ArrayList
		ArrayList<Product> p = new ArrayList<>();
		p.add(new Product("1","啊哈",12.5f,5));
		p.add(new Product("2","hahahah",12.5f,5));
		for(Product pp:p){
			System.out.println(pp);

猜你喜欢

转载自blog.csdn.net/qq_43316411/article/details/88643498