public class Demo {
public static void main(String[] args) {
// 创建集合
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
List<Integer> list3 = new ArrayList<Integer>();
System.out.println(list1);// 结果:[]
System.out.println(list2);// 结果:[]
System.out.println(list3);// 结果:[]
// 1、add(E e) - 向列表的尾部添加指定的元素
list1.add(1);
list1.add(2);
System.out.println(list1);// 结果:[1, 2]
list2.add(3);
list2.add(4);
System.out.println(list2);// 结果:[3, 4]
list3.add(5);
list3.add(6);
System.out.println(list3);// 结果:[5, 6]
// 2、add(int index, E element) - 在列表的指定位置插入指定元素
list1.add(0, 3);
System.out.println(list1);// 结果:[3, 1, 2]
// 3、addAll(Collection c) - 添加指定集合中的所有元素到此列表的结尾
list1.addAll(list2);
System.out.println(list1);// 结果:[3, 1, 2, 3, 4]
// 4、contains(Object o) - 如果列表包含指定的元素,则返回 true
System.out.println(list1.contains(1));// 结果:true
System.out.println(list1.contains(6));// 结果:false
// 5、containsAll(Collection c) - 如果列表包含指定 collection 的所有元素,则返回 true
System.out.println(list1.containsAll(list2));// 结果:true
System.out.println(list1.containsAll(list3));// 结果:false
// 6、equals(Object o) - 比较指定对象与列表是否相等
System.out.println(list1.equals(list1));// 结果:true
System.out.println(list1.equals(list2));// 结果:false
// 7、get(int index) - 返回列表中指定位置的元素
System.out.println(list1.get(0));// 结果:3
// 8、indexOf(Object o) - 返回此列表中第一次出现的指定元素的索引,如果不包含该元素,则返回 -1
System.out.println(list1.indexOf(3));// 结果:0
// 9、lastIndexOf(Object o) - 返回此列表中最后一次出现的指定元素的索引,如果不包含该元素,则返回 -1
System.out.println(list1.lastIndexOf(3));// 结果:3
// 10、isEmpty() - 如果列表不包含元素,则返回 true
System.out.println(list1.isEmpty());
// 11、remove(int index) - 移除列表中指定位置的元素
System.out.println(list1);// 移除前:[3, 1, 2, 3, 4]
list1.remove(0);
System.out.println(list1);// 移除后:[1, 2, 3, 4]
// 12、remove(Object o) - 从此列表中移除第一次出现的指定元素(如果存在)
System.out.println(list1);// 移除前:[1, 2, 3, 4]
list1.remove(new Integer(4));
System.out.println(list1);// 移除后:[1, 2, 3]
// 13、retainAll(Collection c) - 仅在列表中保留指定指定集合中所包含的元素
System.out.println(list1);// [1, 2, 3]
System.out.println(list2);// [3, 4]
System.out.println(list1.retainAll(list2));
System.out.println(list1);// 结果:[3]
// 14、set(int index, E element) - 用指定元素替换列表中指定位置的元素
list1.set(0, 5);
System.out.println(list1);// 结果:[5]
// 15、size() - 返回列表中的元素数
System.out.println(list1.size());//结果:1
}
}
java List集合常用方法
最新推荐文章于 2023-05-11 17:01:38 发布