1.Set集合;

Set集合是Collection接口的子接口,没有对Collection接口进行扩展,里面不允许存在重复的内容;

package Month01.Day14.Demo02;

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

public class TestSet {

	public static void main(String[] args) {
		/**
		 * 1.HashSet是无序的 2.HashSet是不存在重复的
		 */
		HashSet<String> hs = new HashSet<String>();
		hs.add("823");
		hs.add("566");
		hs.add("989");
		hs.add("123uu");

		Iterator<String> it = hs.iterator();
		while (it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}

	}
}

输出结果:

566
123uu
823
989

 

2.Map集合;

是存放一对值的最大接口,即接口中的每一个元素都是一对,以key->value键值对的形式保存;

先建一个student类:

package Month01.Day14.Demo02;

public class Student {

	private String name;
	private Integer age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	// 重写toString方法
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

再建立测试类:

package Month01.Day14.Demo02;

import java.util.HashMap;
import java.util.Iterator;

public class TestMap {

	public static void main(String[] args) {
		/**
		 * 1.HashSet是无序的 2.HashSet是不存在重复的
		 */
		HashMap<String, Student> hm = new HashMap<String, Student>();
		hm.put("1", new Student("张三", 10));
		hm.put("2", new Student("李四", 11));
		hm.put("3", new Student("王五", 12));

		Student s = hm.get("1");
		System.out.println(s);

		// 获取key的集合,再获取迭代器
		Iterator<String> it = hm.keySet().iterator();
		while (it.hasNext()) {
			// 获取key
			String key = it.next();
			// 获取值
			Student sd = hm.get(key);
			System.out.println("key=" + key + ",value=" + sd);
		}

	}
}

输出结果为:

Student [name=张三, age=10]
key=1,value=Student [name=张三, age=10]
key=2,value=Student [name=李四, age=11]
key=3,value=Student [name=王五, age=12]