Java 集合

集合

用于存放不确定数量的变量的类
- Collection
- List
- LinkedList 链表列表 插入和删除效率较高
- ArrayList 数组列表 遍历和随机访问效率较高
- Map
- HashMap
- TreeMap
- Set
- HashSet
- TreeSet
- Collections 对集合操作

泛型

使用<类型名>声明数组中要存放的类型,否则默认为Object类型

迭代器

通过iterator()方法获得该集合的迭代器
- hasNext() 是否有下一个元素
- next() 返回下一个元素

List

class Test{
    public static void main(String[] args){
        ArrayList<Integer> al = new ArrayList<>();
        al.add(1);
        al.add(2);
        al.forEach(System.out::print); // 12

        Iterator<Integer> it = al.iterator();
        Integer i = it.next();
        System.out.println(i); // 1

        LinkedList<Integer> ll = new LinkedList<>();
        ll.add(1);
        ll.addFirst(2);
        ll.forEach(System.out::print); // 21
    }
}

List排序

使用list.sort()进行排序操作
被排序的对象需要实现Comparable接口,或者在sort方法中传入比较器参数

class Test{
    public static void main(String []args){
        List<Integer> l = new ArrayList<>();
        l.add(1);
        l.add(2);
        l.sort(Comparator.comparing(i -> i));
        l.forEach(System.out::print); // 12
        l.sort(Comparator.comparing(i -> -i));
        l.forEach(System.out::print); // 21
    }
}

Set

Set接口存储不重复且无序的对象
- 没有get方法,通过iterator遍历

class Test{
    public static void main(String[] args){
        HashSet<Integer> hs = new HashSet<>();
        hs.add(1);
        hs.add(2);
        hs.forEach(System.out::print); // 12

        Iterator<Integer> it = hs.iterator();
        Integer i = it.next();
        System.out.println(i); // 1
    }
}

Map

Map接口存储键值对
键不可重复,可以通过键获得对应的值

class Test{
    public static void main(String[] args){
        HashMap<Integer, String> hm = new HashMap<>();
        hm.put(1, "a");
        hm.put(2, "b");
        hm.put(3, "c");
        hm.forEach((key, val) -> System.out.print(key + "" + val)); // 1a2b3c 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值