[Java] Arraylist common method of operation

Arraylist

The length of the array can not be changed.
ArrayList but the length can be set arbitrarily changed.

For ArrayList, there is an angle bracket on behalf of generics.
Generic: all the elements that is installed in the collection among, all what type of uniform.
Note: Generics can only be a reference type , not a basic type.

Note:
For the ArrayList collection, the direct print address value is not obtained, but the content.
If the content is empty, empty is obtained in parentheses: []


// 创建了一个ArrayList集合,集合的名称是list,里面装的全都是String字符串类型的数据
// 备注:从JDK 1.7+开始,右侧的尖括号内部可以不写内容,但是<>本身还是要写的。
ArrayList<String> list = new ArrayList<>();

Arraylist common method

/*
public boolean add(E e):向集合当中添加元素,参数的类型和泛型一致。返回值代表添加是否成功。
备注:对于ArrayList集合来说,add添加动作一定是成功的,所以返回值可用可不用。
但是对于其他集合(今后学习)来说,add添加动作不一定成功。

public E get(int index):从集合当中获取元素,参数是索引编号,返回值就是对应位置的元素。

public E remove(int index):从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素。

public int size():获取集合的尺寸长度,返回值是集合中包含的元素个数。
*/
public class Demo03ArrayListMethod {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        System.out.println(list); // []

        // 向集合中添加元素:add
        boolean success = list.add("柳岩");
        System.out.println(list); // [柳岩]
        System.out.println("添加的动作是否成功:" + success); // true

        list.add("高圆圆");
        list.add("赵又廷");
        list.add("李小璐");
        list.add("贾乃亮");
        System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 李小璐, 贾乃亮]

        // 从集合中获取元素:get。索引值从0开始
        String name = list.get(2);
        System.out.println("第2号索引位置:" + name); // 赵又廷

        // 从集合中删除元素:remove。索引值从0开始。
        String whoRemoved = list.remove(3);
        System.out.println("被删除的人是:" + whoRemoved); // 李小璐
        System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 贾乃亮]

        // 获取集合的长度尺寸,也就是其中元素的个数
        int size = list.size();
        System.out.println("集合的长度是:" + size);
    }
}

Basic data types used Arraylist

The basic data types need to first become Package Type


import java.util.ArrayList;

/*
如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。

基本类型    包装类(引用类型,包装类都位于java.lang包下)
byte        Byte
short       Short
int         Integer     【特殊】
long        Long
float       Float
double      Double
char        Character   【特殊】
boolean     Boolean

从JDK 1.5+开始,支持自动装箱、自动拆箱。

自动装箱:基本类型 --> 包装类型
自动拆箱:包装类型 --> 基本类型
 */
public class Demo05ArrayListBasic {

    public static void main(String[] args) {
        ArrayList<String> listA = new ArrayList<>();
        // 错误写法!泛型只能是引用类型,不能是基本类型
        //ArrayList<int> listB = new ArrayList<>();
        ArrayList<Integer> listC = new ArrayList<>();
        listC.add(100);
        listC.add(200);
        System.out.println(listC); // [100, 200]

        int num = listC.get(1);
        System.out.println("第1号元素是:" + num);
    }
}
Published 218 original articles · won praise 6 · views 20000 +

Guess you like

Origin blog.csdn.net/u011035397/article/details/104953785