List接口:有序、有下标、元素可重复
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Demo03 {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList<>();
//添加元素
list.add("cat");
list.add("dog");
list.add(0,"sheep"); //向指定索引添加元素
System.out.println("元素个数:" + list.size());
System.out.println(list.toString());
//删除元素
list.remove(0);
System.out.println("删除后:" + list.size());
System.out.println(list.toString());
//遍历
//for
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
//foreach
for (Object object: list) {
System.out.println(object);
}
//迭代器
Iterator it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//列表迭代器
ListIterator lit = list.listIterator();
while(lit.hasNext()){ //从前往后
System.out.println(lit.nextIndex() + ":" + lit.next());
}
while(lit.hasPrevious()){ //从后往前
System.out.println(lit.previousIndex() + ":" + lit.previous());
}
//判断
System.out.println(list.contains("cat"));
System.out.println(list.isEmpty());
//获取位置
System.out.println(list.indexOf("cat"));
}
}
import java.util.ArrayList;
import java.util.List;
public class Demo05 {
public static void main(String[] args) {
//创建集合
List list = new ArrayList();
//添加数字数据(自动装箱)
list.add(2);
list.add(4);
list.add(5);
list.add(1);
list.add(3);
System.out.println("元素个数:" + list.size());
System.out.println(list.toString());
//删除
//list.remove(0); //使用下标
//list.remove(new Integer(2));
System.out.println("删除后:" + list.toString());
//subList 返回子集合,含头不含尾
List subList = list.subList(1,3);
System.out.println(subList);
}
}