For循環(huán)和While循環(huán)的區(qū)別是什么

For循環(huán)和While循環(huán)的區(qū)別是什么,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

為華鎣等地區(qū)用戶提供了全套網(wǎng)頁設計制作服務,及華鎣網(wǎng)站建設行業(yè)解決方案。主營業(yè)務為成都網(wǎng)站設計、成都網(wǎng)站制作、華鎣網(wǎng)站設計,以傳統(tǒng)方式定制建設網(wǎng)站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!

最簡單的情況是對列表中的每個元素執(zhí)行操作。

List<Integer> list = List.of(1, 2, 3); // bare for loop.  for(int i : list) {    System.out.println("int = "+ i); }// controlled for each list.forEach(i -> System.out.println("int = " + i));

在這種最簡單的情況下,無論哪種方法都沒有太大優(yōu)勢。但第二種方法可以不使用bare for循環(huán),而且語法更簡潔。

我覺得forEach語句也有問題,應該只應用于副作用安全的方法。我所說的安全副作用是指不改變程序狀態(tài)。上例只是記錄日志,因此使用無礙。其他有關(guān)安全副作用的示例是寫入文件、數(shù)據(jù)庫或消息隊列。

不安全的副作用會更改程序狀態(tài)。下面為示例及其解決方法:

// bad side-effect, the loop alters sum int sum = 0; for(int i : list) {     sum += i; } System.out.println("sum = " + sum);// no side-effect, sum iscalculated by loop sum = list        .stream()        .mapToInt(i -> i)        .sum(); System.out.println("sum = " + sum);

另一個常見的例子:

// bad side-effect, the loop alters list2 List<Integer> list2 = new ArrayList<>(); for(int i : list) {    list2.add(i); } list2.forEach(i -> System.out.println("int = " + i));// no sideeffect, the second list is built by the loop list2 = list          .stream()          .collect(Collectors.toList()); list2.forEach(i -> System.out.println("int = " + i));

當你需要處理列表項方法中的索引時就會出現(xiàn)問題,但可以解決,如下:

// bare for loop with index: for(int i = 0; i < list.size(); i++) {     System.out.println("item atindex "        + i        + " = "        + list.get(i)); }// controlled loop with index: IntStream.range(0, list.size())    .forEach(i ->System.out.println("item at index "     + i     + " = "     + list.get(i)));

老生常談的問題:讀取文件中的每一行直到文件讀取完畢如何解決?

BufferedReader reader = new BufferedReader(        new InputStreamReader(       LoopElimination.class.getResourceAsStream("/testfile.txt"))); // while loop with clumsy looking syntax String line; while((line = reader.readLine()) != null) {    System.out.println(line); }reader = new BufferedReader(        new InputStreamReader(       LoopElimination.class.getResourceAsStream("/testfile.txt"))); // less clumsy syntax reader.lines()    .forEach(l ->System.out.println(l));

應對上述情況有一個非常簡便的lines方法,可以返回Stream類型。但是如果一個字符一個字符地讀取呢?InputStream類沒有返回Stream的方法。我們必須創(chuàng)建自己的Stream:

InputStream is =    LoopElimination.class.getResourceAsStream("/testfile.txt"); // while loop with clumsy looking syntax int c; while((c = is.read()) != -1) {   System.out.print((char)c); } // But this is even uglier InputStream nis =    LoopElimination.class.getResourceAsStream("/testfile.txt"); // Exception handling makes functional programming ugly Stream.generate(() -> {    try {       return nis.read();    } catch (IOException ex) {       throw new RuntimeException("Errorreading from file", ex);    } })  .takeWhile(ch -> ch != -1)  .forEach(ch ->System.out.print((char)(int)ch));

這種情況下while循環(huán)看起來更好。此外,Stream版本還使用了可以返回無限項目流的  generate函數(shù),因此必須進一步檢查以確保生成過程終止,這是由于takeWhile方法的存在。

InputStream類存在問題,因為缺少peek  方法來創(chuàng)建可輕松轉(zhuǎn)換為Stream的Iterator。它還會拋出一個檢查過的異常,這樣函數(shù)式編程就會雜亂無章。在這種情況下可以使用while語句讓PR通過。

為了使上述問題更簡潔,可以創(chuàng)建一個新的IterableInputStream類型,如下:

static class InputStreamIterable implements Iterable<Character> {   private final InputStream is;   public InputStreamIterable(InputStreamis) {     this.is = is;   }   public Iterator<Character>iterator() {      return newIterator<Character>() {                       public boolean hasNext() {            try {              // poor man's peek:              is.mark(1);              boolean ret = is.read() !=-1;              is.reset();              return ret;            } catch (IOException ex) {              throw new RuntimeException(                     "Error readinginput stream", ex);            }         }         public Character next() {            try {              return (char)is.read();            } catch (IOException ex) {              throw new RuntimeException(                    "Error readinginput stream", ex);            }         }      };   } }

這樣就大大簡化了循環(huán)問題:

// use a predefined inputstream iterator: InputStreamIterable it = new InputStreamIterable(     LoopElimination.class.getResourceAsStream("/testfile.txt")); StreamSupport.stream(it.spliterator(), false)    .forEach(ch -> System.out.print(ch));

如果你經(jīng)常遇到此類while循環(huán),那么你可以創(chuàng)建并使用一個專門的Iterable類。但如果只用一次,就不必大費周章,這只是新舊Java不兼容的一個例子。

關(guān)于For循環(huán)和While循環(huán)的區(qū)別是什么問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

本文題目:For循環(huán)和While循環(huán)的區(qū)別是什么
文章分享:http://muchs.cn/article16/iepgdg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名網(wǎng)站改版小程序開發(fā)、品牌網(wǎng)站設計、響應式網(wǎng)站、移動網(wǎng)站建設

廣告

聲明:本網(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)

外貿(mào)網(wǎng)站制作