Iterator & Iterable 和 Comparable&Comparator

java.lang.Iterator & java.lang.Iterable

Iterator和Iterable的区别和联系

iterator是具有迭代状态的对象。它允许你检查它是否有更多的元素使用hasNext()并移动到下一个元素(如果有)使用next()。

Iterable是可以迭代的一系列元素的简单表示。它没有任何迭代状态,如“当前元素”。相反,它有一种产生迭代器的方法。通常,Iterable应该能够生成任意数量的有效迭代器。也就是说:Iterator是迭代器,可以对可以迭代的对象集合进行遍历操作。而Iterable表示集合是可以迭代的,并提供了产生迭代器的方法。

Iterator<E>方法

  • boolean hasNext();

判断是否有下一个元素存在

  • E next();

返回集合的下一个元素

  • default void remove() {throw new UnsupportedOperationException("remove");}

移除元素

  • default void forEachRemaining(Consumer<? super E> action) {... ...}

遍历集合元素。java8新增方法。同时也是java8新增的一个特性(接口中对于默认方法:default修饰的可以有实现)

Iterable<E>方法

  • Iterator<T> iterator();

返回迭代器

  • default void forEach(Consumer<? super T> action) {... ... }

集合遍历,java8新增方法。

  • default Spliterator<T> spliterator() {... ... }

java.lang.Comparable & java.lang.Comparator

Comparable和Comparator的区别和联系

Comparable表示实现该接口的类是可排序的,并提供了排序方法compareTo(Objec o)。实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。

Comparator表示比较器接口,提供了compare(Objec o1,Obect o2)和equals(Object o)方法。由于equals(Object o)方法已经由Object类提供,所以实现Comparator接口的类可以不用显示指定。

实现Comparable接口的类需要实现compareTo(Objec o)方法。在排序时一般使用Collections.sort()或者Arrays.sort()方法来排序。对于Integer、Long等可比较大小的类jdk中已经默认实现了comparable接口,所以可以直接使用。一般称Comparable为内部比较器。

实现Comparator接口的类需要实现compare(Object o1,Object o2)方法。在排序时如果使用Collections.sort(Arrays.sort())方法需要显示指定Comparator实现类。具体函数如下:

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

一般称Comparator为外部比较器。

Comparable和Comparator的用法

Comparable
1.自然排序

List<Integer> list = Arrays.asList(1,232,32,2,45);
Collections.sort(list);
list.forEach(System.out::println);

2.自定义排序

People p1 = new People(12,"sdf");
People p2 = new People(22,"ssdf");
People p3 = new People(10,"sdsf");
People p4 = new People(32,"sd12f");
List<People> peopleList = Arrays.asList(p1,p2,p3,p4);
Collections.sort(peopleList);
peopleList.forEach(people-> System.out.println(people));

 其中:People需要继承接口Comparable:

public class People implements Comparable{
            @Override
            public int compareTo(Object o) {
                People p = (People)o;
                return this.getAge().compareTo(p.getAge());
            }
}

Comparator

        People p1 = new People(12,"sdf");
        People p2 = new People(22,"ssdf");
        People p3 = new People(10,"sdsf");
        People p4 = new People(32,"sd12f");
        List<People> peopleList = Arrays.asList(p1,p2,p3,p4);
        Collections.sort(peopleList, new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                return o1.getAge().compareTo(o2.getAge());
            }
        });
        peopleList.forEach(people-> System.out.println(people)); 
原文地址:https://www.cnblogs.com/uodut/p/7581780.html