本文主要是介绍单列集合--List,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方法演示:
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);}
}
这篇关于单列集合--List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!