Java List部分截取,獲得指定長度子集合


subList方法用於獲取列表中指定范圍的子列表,該列表支持原列表所支持的所有可選操作。返回列表中指定范圍的子列表。

 語法 

        subList(int fromIndex, int toIndex) 

        fromIndex:用於指定新列表的起始點(包括該點)。

        toIndex:用於指定新列表的結束點(不包括該點)。

用法實例:

    public static void main(String[] args) {
                         List<String> list = new ArrayList<String>();
                          list.add("貓");        //向列表中添加數據
                          list.add("狗");        
                          list.add("豬");       
                          list.add("鴨子");        
                          list.add("雞");         
                          list.add("猴子");      
                     Iterator<String> its = list.iterator();    //迭代list
                       System.out.println("集合中所有元素對象:");
                                while (its.hasNext()) {        //循環遍歷集合
                                          System.out.print(its.next() + "  ");     //輸出集合內容
                                        }
                  List<String> subList = list.subList(3, 5);    //獲取子列表
                  System.out.println("\n截取集合中部分元素:");
                        Iterator it = subList.iterator();
                            while (it.hasNext()) {
                                  System.out.print(it.next() + "  ");
                             }
                }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM