方法演示:
package exercise;
import java.util.ArrayList;
import java.util.List;
public class ListDemo1 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add("java");
System.out.println(list);
list.add(1, "javaee");
System.out.println(list);
String remove = list.remove(2);
System.out.println(remove + " " + list);
String javaSe = list.set(1, "javaSe");
System.out.println(javaSe + " " + list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
}
tips:
package exercise;
import java.util.ArrayList;
import java.util.List;
public class ListDemo2 {
public static void main(String[] args) {
//List集合中的两个删除方法
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
//当方法出现重载时,优先调用形参和实参类型一致的那个方法。
list.remove(1);
System.out.println(list);
//如不想这样,则需要手动装箱
Integer i = Integer.valueOf(1);
list.remove(i);
System.out.println(list);
}
}
方法演示:
package exercise;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ListDemo3 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add("java");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
System.out.println("=======");
for (String s : list) {
System.out.println(s);
}
System.out.println("=======");
list.forEach(s -> System.out.println(s));
System.out.println("=======");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("=======");
//相比迭代器,额外添加了一个方法。在遍历过程中,可以添加元素
ListIterator<String> s = list.listIterator();
while (s.hasNext()) {
String str = s.next();
if ("world".equals(str)) {
s.add("javaee");
}
}
System.out.println(list);
}
}