Set集合

set集合概述

单列位于Collection下是一个接口

特定:无序,不可重复,没有带索引的方法,所以不能使用普通for循环遍历

import java.util.HashSet;
import java.util.Set;
//特定:无序,不可重复,没有带索引的方法,所以不能使用普通for循环遍历
//用set集合并储存字符串
public class E10 {
    public static void main(String[] args) {
        //创建集合对象
        Set<String> s = new HashSet<String>();

        //添加元素
        s.add("hello");
        s.add("world");
        s.add("he");
        //不带索引
        //不可重复
        s.add("he");
        
        //world
        //hello
        //he

        //遍历
        for (String s1 : s) {
            System.out.println(s1);
        }
        //world hello he
        //顺序是不同的,HasSet不对顺序有要求
    }
}

##### **哈希值**

哈希值:JDK根据对象的地址或字符串或数字是算出的int类型的数字

public class E11 {
    public static void main(String[] args) {
        //创建一个对象
        student s1 = new student();
        student s2 = new student();
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        //21685669
        //2133927002
        System.out.println("hello".hashCode());
        System.out.println("java".hashCode());
        //99162322
        //3254818

    }
}

class student{
    void eat(){
        System.out.println("ss");
    }

}

2021-03-15 18:58:09

posted @ 2021-03-15 18:58  域明夜  阅读(59)  评论(0)    收藏  举报