集合类的特点:提供一种存储空间可变的存储模型,存储数据容量可以发生改变
ArrayList:
可调整大小的数组类实现
代表着泛型
public ArrayList(): 创建空的对象
public boolean add(E e):将指定的元素加到对象的末尾
public void add(int index,E e):将指定的元素加到指定的位置
public static void main(String[] args) {
//创建一个空的集合对象
ArrayList<String> arr = new ArrayList<String>();
System.out.println(arr);//[]
//使用add添加对象
arr.add("Hello");
arr.add("world");
arr.add(0,"nihao");
System.out.println(arr);//[nihao, Hello, world]
}
public boolean remove(object o):删除指定元素,返回是否删除成功
public E remove(int index):删除指定位置元素,返回被删除的元素
public E set(int index,E element):将指定位置元素进行修改,返回被修改的元素
public E get(int index):返回指定位置的元素
public int size()返回集合中元素的个数
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add("hello");
arr.add("world");
arr.add("java");
arr.add("move");
System.out.println(arr);//[hello, world, java, move]
System.out.println(arr.remove("he"));//false
System.out.println(arr);//[hello, world, java, move]
System.out.println(arr.remove("move"));//true
System.out.println(arr);//[hello, world, java]
// System.out.println(arr.remove(3));//java.lang.IndexOutOfBoundsException
System.out.println(arr.remove(1));//world
System.out.println(arr);//[hello, java]
System.out.println(arr.get(1));//java
// System.out.println(arr.set(2,"world"));//java.lang.IndexOutOfBoundsException
System.out.println(arr.set(1,"world"));//java
System.out.println(arr);//[hello, world]
System.out.println(arr.size());//2
}
实例:遍历ArrayList元素
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<>();
arr.add("Hello");
arr.add("World");
arr.add("LIST");
arr.add("java");
arr.add("miss");
showArrayList(arr);
}
public static void showArrayList(ArrayList list){
//遍历ArrayList
//size:获取ArrayList长度
//get(index):获取ArrayList对应的值
for(int i = 0;i < list.size();i++){
System.out.println(list.get(i));
//Hello
//World
//LIST
//java
//miss
}
}