HashMap与HashSet的简单实例

HashSet存储的是无序的,唯一的集合,可以用迭代器遍历。
HashMap存储的是两两对应的映射关系。
下面进行一些小测试

public class MapSet {
    public MapSet() {
    }

    Set str=new HashSet();
    String s1="hhh";
    String s2="88";
    String s3="hhh";
    String s4="t";
    int n1=88;
    char c1='t';
    short n2=88;

    void setset(){
        str.add(s1);
        str.add(s2);
        str.add(s3);//和上面值一样,视为相同
        str.add(s4);
        s4="ls";
        str.add(s4);//两次值不同,视为不同
        str.add(n1);//int和String 类型不同,视为不同
        str.add(c1);//虽然都是t,类型不同,视为不同
        str.add(n2);//虽然都是88,int和short,视为不同
    }
    void getsize(){
        System.out.println(str.size());
    }

    void showall(){
        Iterator it=str.iterator();
        while(it.hasNext()){        //迭代器遍历
            System.out.print(it.next()+" ");
        }
        System.out.println();
        for(Object str:str){        //增强型for遍历
            System.out.print(str+" ");
        }
    }

    Map map=new HashMap();
    void setmap(){
        map.put("苹果","apple");
        map.put("菠萝","pineapple");
        map.put("香蕉","banana");
        map.put("火龙果","pitaya");
        map.put("榴莲","durian");
    }

    void getmap(String s){
        System.out.print(map.get(s)+" ");
    }
}

猜你喜欢

转载自blog.csdn.net/dt_zhangshuo/article/details/81206984