Container and its method of learning set

package com.wyq.StringBuffer;

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

public class TestSet {
	public static void main(String[] args) {
		//添加泛型,在创建对象的时候,就明确了集合中只能存储String类型的对象
		Set<String> set = new HashSet<String>();
		/**
		 * [1]向集合中添加元素
		 */
		set.add("hello");
		set.add("world");
		set.add("java");
		set.add("python");
		set.add("hello");
		System.out.println(set.add("计算机"));
		System.out.println(set.add("hello"));
		System.out.println(set);
		System.out.println("集合中的元素是否为空:"+set.isEmpty()+"\t集合中元素的个数为:"+set.size()+"\t集合是否包含:"+set.contains("java"));
		/**
		 * 由以上看出,set集合中的元素是无需并且唯一的
		 */
//		set.remove("java");
//		System.out.println(set.remove("python"));
		System.out.println(set);
		System.out.println(set.containsAll(set));
//		set.clear();
		System.out.println(set);
		Iterator ite = set.iterator();
		System.out.println("使用while循环输出");
		while(ite.hasNext()){
			System.out.println(ite.next());
		}
		System.out.println("使用迭代for循环输出");
		for(Iterator it = set.iterator();it.hasNext();){
			System.out.println(it.next());
		}
		System.out.println("使用加强for循环输出");
		for(String obj:set){//这里的类型可以是String类型,也可以是object类型
			System.out.println(obj);
		}
		/**
		 * 由于set不支持按照索引获取数值,所以暂时不支持使用普通for循环输出
		 */
	}
}

 

Guess you like

Origin blog.csdn.net/wyqwilliam/article/details/93335935