kooyee ‘s blog

          開源軟件, 眾人努力的結(jié)晶, 全人類的共同財富
          posts - 103, comments - 55, trackbacks - 0, articles - 66
             :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          [J2SE] For-each 循環(huán)

          Posted on 2007-07-25 19:56 kooyee 閱讀(265) 評論(0)  編輯  收藏 所屬分類: Java

          Java 5 之后終于能在java中使用for each 循環(huán)

          for (type var : arr) {
              body
          -of-loop
          }

          for (int i = 0; i < arr.length; i++
              type var 
          = arr[i];
              body
          -of-loop
          }


          For-each loop Equivalent for loop
          for (type var : arr) {
                      body-of-loop
                      }
          for (int i = 0; i < arr.length; i++) {
                      type var = arr[i];
                      body-of-loop
                      }
          for (type var : coll) {
                      body-of-loop
                      }
          for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
                      type var = iter.next();
                      body-of-loop
                      }


          Where the for-each is appropriate

          Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.

          • Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
          • Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
          • Only single element. Use only for single element access, eg, not to compare successive elements.
          • Only forward. It's possible to iterate only forward by single steps.
          • At least Java 5. Don't use it if you need compatibility with versions before Java 5.

          看來只能讀取, 而不能寫入值。而且不能進(jìn)行太復(fù)雜的操作。

          主站蜘蛛池模板: 颍上县| 三门县| 博兴县| 扶风县| 康保县| 山阳县| 福安市| 周至县| 句容市| 孝感市| 永胜县| 准格尔旗| 新野县| 西充县| 河北区| 乌苏市| 石家庄市| 桦甸市| 新建县| 仙居县| 保定市| 丹阳市| 巴里| 调兵山市| 任丘市| 九江市| 陇南市| 陕西省| 洮南市| 涞水县| 天峻县| 昌邑市| 乌兰浩特市| 曲周县| 崇仁县| 潞城市| 普兰店市| 安阳县| 武定县| 子长县| 平顺县|