Set集合,HashSet集合,TreeSet集合,

Set接口:

一个不包含重复元素的 collection。
数据无序(因为set集合没有下标)。
由于集合中的元素不可以重复。常用于给数据去重。

方法:
boolean add(E e):添加元素。
boolean addAll(Collection c):把小集合添加到大集合中 。
boolean contains(Object o) : 如果此 collection 包含指定的元素,则返回 true。
boolean isEmpty() :如果此 collection 没有元素,则返回 true。
Iterator iterator():返回在此 collection 的元素上进行迭代的迭代器。
boolean remove(Object o) :从此 collection 中移除指定元素的单个实例。
int size() :返回此 collection 中的元素数。
Objec[] toArray():返回对象数组

代码:

package day20200819;

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

public class Demo02 {
    
    
	public static void main(String[] args) {
    
    
		// set
		Set<String> set1 = new HashSet<String>();
		set1.add("apple");
		set1.add("banana");
		set1.add("orange");
		set1.add("orange");
		System.out.println(set1);
		Set<String> set2 = new HashSet<String>();
		set2.add("dog");
		set2.add("pig");
		set2.add("chicken");
		set1.addAll(set2);
		System.out.println(set1);
		System.out.println(set1.contains("fruit"));
		System.out.println(set1.isEmpty());
		Iterator<String> itera = set1.iterator();
		while (itera.hasNext()) {
    
    
			System.out.println(itera.next());
		}

		set1.remove("pig");
		System.out.println(set1);

		System.out.println(set1.size());
		
		Object[] array = set1.toArray();
		for(Object obj : array){
    
    
			System.out.println(obj);
		}
		
		
		

	}

}

Guess you like

Origin blog.csdn.net/qq_43472248/article/details/108107992