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() + "? ");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? }
轉載于:https://www.cnblogs.com/TheGCC/p/8840256.html
總結
以上是生活随笔為你收集整理的Java List部分截取,获得指定长度子集合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 零信任技术进阶篇(关键技术及挑战、Bey
- 下一篇: Python__random库基本介绍