午夜无码人妻aⅴ大片色欲张津瑜,国产69久久久欧美黑人A片,色妺妺视频网,久久久久国产综合AV天堂

使用Java如何自定義一個迭代器

使用Java如何自定義一個迭代器?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供橋西網(wǎng)站建設、橋西做網(wǎng)站、橋西網(wǎng)站設計、橋西網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、橋西企業(yè)網(wǎng)站模板建站服務,十載橋西做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。

具體如下:

編寫自己的Iterator,實現(xiàn)Iterator接口,這里多說一句,實現(xiàn)Iterable后,可以用“foreach”循環(huán)遍歷你的對象。

import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * 演示Iterator和Iterable接口,并說明怎樣編寫一個用于對象數(shù)組的簡單迭代器。
 */
public class AarrayIterator<T> implements Iterable<T>, Iterator<T> {
  private final static String[] names = {"rose", "petunia", "tulip"};
  public static void main(String[] args) {
    AarrayIterator<String> arrayIterator = new AarrayIterator<>(names);
    // Java 5,6的方式
    for (String s : arrayIterator) {
      System.out.println(s);
    }
    // Java 8的形式
    arrayIterator.forEach(System.out::println);
  }
  /**
   * 要遍歷的數(shù)據(jù)
   **/
  protected T[] data;
  protected int index = 0;
  /**
   * 構(gòu)造一個AarryIterator對象。
   *
   * @param data 被迭代的對象數(shù)組
   */
  public AarrayIterator(final T[] data) {
    setData(data);
  }
  /**
   * 設置(重置)數(shù)組為給定的數(shù)組,重置迭代器。
   * 參數(shù)d代表被迭代的數(shù)組對象。
   *
   * @param d 被迭代的數(shù)組對象
   */
  public void setData(final T[] d) {
    this.data = d;
    index = 0;
  }
  /**
   * 如果不是末尾,返回true,例如,if next()語句將成功執(zhí)行。
   * 否則返回false,執(zhí)行if next()語句會拋出異常。
   *
   * @return
   */
  public boolean hasNext() {
    return index < data.length;
  }
  /**
   * 返回該數(shù)據(jù)的下一個元素
   *
   * @return
   */
  public T next() {
    if (hasNext()) {
      return data[index++];
    }
    throw new NoSuchElementException("only " + data.length + " elements");
  }
  public void remove() {
    throw new UnsupportedOperationException("This demo Iterator does not implement the remove method");
  }
  /**
   * Iterator的方法
   *
   * @return
   */
  public Iterator<T> iterator() {
    index = 0;
    return this;
  }
}

執(zhí)行結(jié)果:

rose
petunia
tulip
rose
petunia
tulip

關(guān)于使用Java如何自定義一個迭代器問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

標題名稱:使用Java如何自定義一個迭代器
文章URL:http://www.ekvhdxd.cn/article48/pjeiep.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站全網(wǎng)營銷推廣、外貿(mào)建站、動態(tài)網(wǎng)站、標簽優(yōu)化、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設網(wǎng)站維護公司