list
创建
List<String> list = new ArrayList<String>();
添加元素
list.add("Hello");
list.add(2,"!");
获取容量
System.out.println("ArrayList当前容量:"+list.size());
打印当前内容
System.out.println("ArrayList当前内容:"+list.toString());
修改
list.set(0,"my");
判断功能:
boolean isEmpty = list.isEmpty();//判断是否为空
boolean isContain = list.contains("my");//判断是否存在 对象
把集合转换成数组
String[] strArray = list.toArray(new String[]{}); System.out.println(strArray[0]+ strArray[1]+strArray[2]);
删除功能:
list.remove(0);
list.remove("world");
list.clear();
完整代码
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
System.out.println("ArrayList集合初始化容量:"+list.size());
list.add("Hello");
list.add("world");
list.add(2,"!");
System.out.println("ArrayList当前容量:"+list.size());
System.out.println("ArrayList当前内容:"+list.toString());
list.set(0,"my");
list.set(1,"name");
System.out.println("ArrayList当前内容:"+list.toString());
String element = list.get(0);
System.out.println(element);
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String next = iterator.next();
System.out.println(next);
}
for(String str:list){
System.out.println(str);
}
boolean isEmpty = list.isEmpty();
boolean isContain = list.contains("my");
System.out.println(isEmpty);
System.out.println(isContain);
String[] strArray = list.toArray(new String[]{});
System.out.println(strArray[0]+ strArray[1]+strArray[2]);
list.remove(0);
list.remove("world");
list.clear();
System.out.println("ArrayList当前容量:"+list.size());
}
}
|