阿金
curatorjin
早起赶画稿,熬夜写项目
disciple_sneaker@163.com
相关标签: Java

Set接口的特点


HashSet存储自定义对象并遍历

public class TestForHashSet{
    public static void main(String[] args){
        HashSet<Student> hs = new HashSet<>();                      //创建HashSet集合
        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();
        Student s4 = new Student();
        Student s5 = new Student();                                 //创建学生类对象*5
        hs.add(s1);hs.add(s2);hs.add(s3);hs.add(s4);hs.add(s5);     //将学生对象存入集合中
        for(Student s:hs){
            System.out println(s);                                  //由于HashSet集合没有索引,所以此处用增强for循环来遍历
        }
    }
}

HashSet自动去重原理


实现HashSet存储自定义对象去重


Collections工具类

    - int binarySearch(List list,E e)                   //二分法查找元素
    - void sort(List list)                              //排序  
    - void copy(List dest,List src                      //复制集合
    - void reverse(List list)                           //翻转集合
    - void shuffle(List list)                           //打乱集合
    - void swap(List list, int index1, int index2)      //调换集合中索引为index1和index2的元素的位置
    - void fill(List list, Object obj)                  //以元素obj填充list集合

Map接口的概述


Map的功能概述

Map<K key, V value>                     //Map是一个接口,只能创建其已经实现了的子类对象

V put(K key,V value)                    //以键=值的方式存入Map集合,并将值返回
V get(Object key)                       //根据键值获取其所对应的值,如果Map集合中不存在该键值则返回null
int size()                              //返回Map中键值对的个数

boolean containsKey(Object key)         //判断Map集合中是否包含键值为key的键值对
boolean containsValue(Object value)     //判断Map集合中是否包含值为value的键值对
boolean isEmpty()                       //判断Map集合中是否没有任何键值对

void clear()                            //清空Map集合中所有的键值对
V remove(Object key)                    //根据键值删除Map中的键值对,并将键值对应的值返回

Set<Map.Entry<K,V>> entrySet()          //将Map中的每个键值对封装到一个个的Entry对象中,再将所有的Entry对象存储到一个Set集合中并返回此Set集合
Set<K> keySet()                         //将Map中所有的键值封装到一个Set集合中并返回此Set集合
Collection<V> values()                  //将集合中所有的value的值的集合返回

Map的第一种遍历方式


可变参数