【java学习笔记-24】List常用方法及去重等处理
List的初始化有很多方式,以下是两种常用的:
// 方式1 List myList = new ArrayList(); myList.add("python"); myList.add(1,"java"); myList.add(2,"c++"); // 方式2 List myList = Arrays.asList("java", "c++", "html", "python", "js", "python", "go");
List常用的方法:
package com.course.coke; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ListTest03 { public static void main(String[] args) { List myList = new ArrayList(); myList.add("python"); myList.add(1,"java"); myList.add(2,"c++"); // 清除list中全部元素 // myList.clear(); boolean flag = myList.contains("java"); System.out.println(flag); // 是否相等 boolean flag1 = myList.equals(myList); // 根据下标获取元素 System.out.println(myList.get(2)); // 返回list中首次出现该元素的索引,如果没有返回-1 System.out.println(myList.indexOf("c++")); // 判断list是否为空 boolean flag2 = myList.isEmpty(); System.out.println(flag2); // 根据下标移除元素 myList.remove(1); // 替换指定位置的元素 myList.set(1,"html"); // 返回list中元素的个数 System.out.println(myList.size()); // 返回包含所有元素的数组 System.out.println(Arrays.toString(myList.toArray()));; System.out.println("***************list循环迭代方法①***************"); // list循环迭代方法① for (int i = 0; i < myList.size(); i++) { System.out.println(myList.get(i)); } System.out.println("***************list循环迭代方法②***************"); // list循环迭代方法② Iterator iterator = myList.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } }
处理①:元素去重
package com.course.coke; import java.util.ArrayList; import java.util.List; public class ListTest04 { public static void main(String[] args) { List myList = new ArrayList(); myList.add(0,"java"); myList.add(1,"c++"); myList.add(2,"html"); myList.add(3,"python"); myList.add(4,"js"); myList.add(5,"python"); myList.add(6,"go"); System.out.println("最初的list是:" + myList); List newList = new ArrayList(); for (int i = 0; i < myList.size(); i++) { if (!newList.contains(myList.get(i))){ newList.add(myList.get(i)); } } System.out.println("去重后的list是:" + newList); } }
执行结果是:
最初的list是:[java, c++, html, python, js, python, go]
去重后的list是:[java, c++, html, python, js, go]
处理②:获取前n和元素,或去掉后m个元素(n或者m均不大于list长度)
package com.course.coke; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListTest05 { public static void main(String[] args) { List myList = Arrays.asList("java", "c++", "html", "python", "js", "python", "go"); System.out.println("最初的list是:" + myList); // 截取前3个元素,组成新的list List newList1 = new ArrayList(); for (int i = 0; i < 3; i++) { newList1.add(myList.get(i)); } System.out.println("newList是:" + newList1); // 去掉后3个元素,组成新的list List newList2 = new ArrayList(); for (int i = 0; i < myList.size()-3; i++) { newList2.add(myList.get(i)); } System.out.println("newList是:" + newList2); } }
---------------------------------------------------
立足软件测试领域,并重新定义测试!
---------------------------------------------------