Java集合:Iterable接口

一时失言乱红尘 2023-02-25 02:06 134阅读 0赞

直入主题:先看下相关接口及JDK给出的解释

Iterable接口:

  1. //实现此接口允许对象成为“ for-each循环”语句的目标
  2. public interface Iterable<T> {
  3. //return an Iterator.
  4. Iterator<T> iterator();
  5. //给每个元素执行给定的操作,直到处理完所有元素或该操作引发异常为止。除非额外实现该方法
  6. default void forEach(Consumer<? super T> action) {
  7. Objects.requireNonNull(action);
  8. for (T t : this) {
  9. action.accept(t);
  10. }
  11. }
  12. ...
  13. }

消费者:

  1. //函数式接口
  2. @FunctionalInterface
  3. public interface Consumer<T> {
  4. //对给定的参数执行此操作
  5. void accept(T t);
  6. ...
  7. }

迭代器:

  1. public interface Iterator<E> {
  2. //return true if the iteration has more elements
  3. boolean hasNext();
  4. //Returns the next element in the iteration
  5. E next();
  6. ...
  7. }

OK!,接口观察完毕,我们参照ArrayList对这三个接口的实现来定义一个我们的接口。
To do!
每个接口主要方法都需要主动实现
Consumer接口是函数接口,可以使用Lamda表达式

  1. public class CollectionTest {
  2. public static void main(String[] args) {
  3. new myArray().forEach((t)->{
  4. System.out.println(t);
  5. });
  6. //上面等同于下面
  7. new myArray().forEach(
  8. new Consumer() {
  9. @Override
  10. public void accept(Object o) {
  11. System.out.println(o);
  12. }
  13. }
  14. );
  15. }
  16. }
  17. class myArray implements Iterable{
  18. private int[] data = { 1,2,3,4,5} ;
  19. int size = data.length;
  20. //需要自己实现
  21. @Override
  22. public Iterator iterator() {
  23. return new myIterator();
  24. }
  25. //foreach的内部还是for循环
  26. @Override
  27. public void forEach(Consumer action) {
  28. for (int d : data) {
  29. action.accept(d);
  30. }
  31. }
  32. //简单的下标检查+数值返回
  33. private class myIterator implements Iterator{
  34. int cursor = 0;
  35. @Override
  36. public boolean hasNext() {
  37. return cursor!=size;
  38. }
  39. @Override
  40. public Object next() {
  41. return (int)data[cursor];
  42. }
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,134人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Iterator接口

    1.遍历Collection的两种方式 ① 使用迭代器Iterator ② foreach循环(或增强for循环) 2.java.utils包下定义的迭代器接口:

    相关 IteratorIterable接口

    Java为了方便编程,预定义了一些特定功能的接口,本文旨在保存和说明这些接口的功能和作用,也会尽量配合源码进行说明,这个会分成多篇文章进行说明,希望大家能够从中获得自己想要的知