Java-set集合

时间:2021-02-04 12:01:01

package exception;

import  java.util.Map;
import java.util.TreeMap;
import java.util.HashMap; public class TestMap { public static void main(String[] args) {
//map Map<String,String> m1 = new HashMap<>(); //添加数据
//key不能重复
m1.put("0531","济南");
m1.put("0532","青岛");
m1.put("0533","淄博");
m1.put("","章丘"); //如果key重复,那么新的value覆盖旧的value //长度
System.out.println(m1.size()); //获取数据
System.out.println(m1.get("0531")); //移除
m1.remove("0532");
System.out.println(m1.size()); System.out.println("key是否存在="+m1.containsKey("0533")); System.out.println(m1.get(m1.keySet())); //遍历
//通过遍历key的set集合,同事获取value
for(String k:m1.keySet())
{
System.out.println(m1.get(k));
} //TreeMap
TreeMap<Integer,Person> tm =new TreeMap<>(); tm.put(100, new Person("X",20));
tm.put(110, new Person("Y",23));
tm.put(104, new Person("Z",20));
tm.put(102, new Person("W",21)); //遍历
for(Integer k:tm.keySet())
{
System.out.println("ke="+k+"value"+tm.get(k));
} } }

package exception;

import java.util.Set;
import java.util.HashSet;
import java.util.Iterator; public class Test04 { public static void main(String[] args){ //set集合
//实现类HashSet 哈希Hash
//搜索引擎,利用哈希值
//不能存放重复数据
//没有顺序和索引
Set<Person> s1=new HashSet<>(); Person p0=new Person("A",20);
Person p1=new Person("b",20);
Person p2=new Person("c",20); //不能存放重复数据,也不报错
s1.add(p0);
s1.add(p1);
s1.add(p2); s1.add(new Person("B",30)); System.out.println(s1.size()); System.out.println(s1.contains(p0)); s1.remove(p0); System.out.println(s1.size()); System.out.println(s1.contains(p0)); for(Person a:s1)
{
System.out.println(a);
} //迭代器
Iterator<Person> it = s1.iterator();
//
while(it.hasNext())
{
Person p = it.next();
System.out.println(p);
}
} }
package exception;

import java.util.Set;
import java.util.TreeSet;
import java.util.HashSet;
import java.util.Iterator; public class Test04 { public static void main(String[] args){ //set集合
//实现类HashSet 哈希Hash
//搜索引擎,利用哈希值
//不能存放重复数据
//没有顺序和索引
Set<Person> s1=new HashSet<>(); Person p0=new Person("A",20);
Person p1=new Person("b",20);
Person p2=new Person("c",20); //不能存放重复数据,也不报错
s1.add(p0);
s1.add(p1);
s1.add(p2); s1.add(new Person("B",30)); System.out.println(s1.size()); System.out.println(s1.contains(p0)); s1.remove(p0); System.out.println(s1.size()); System.out.println(s1.contains(p0)); for(Person a:s1)
{
System.out.println(a);
} //迭代器
Iterator<Person> it = s1.iterator();
//
while(it.hasNext())
{
Person p = it.next();
System.out.println(p);
} //TreeSet
TreeSet<String> ts= new TreeSet<>(); ts.add("Z");
ts.add("X");
ts.add("B");
ts.add("C");
ts.add("Y");
ts.add("W");
ts.add("M");
ts.add("A");
//ts.addAll(null); for(String str:ts)
{
System.out.println(str);
}
}
}