Java ArrayList collection (Java dynamic array)


1. Overview and basic use of ArrayList collection

1 Overview

ArrayList is an implementation of collection, and Collection is the parent class of all collection classes.
Since the length of the array cannot be changed during runtime, there is an ArrayList collection.

2. Basic use

Create an ArrayList collection

import java.util.ArrayList;//不要忘记导包
//<E>代表泛型,E可以定义为所有的引用类型,例如String、类等
ArrayList<E> list = new ArrayList<>();

Convert other types of collections to ArrayList

ArrayList<String> setList = new ArrayList<>(new HashSet())

Commonly used method
(1) Add data-add()

ArrayList<String> list = new ArrayList<>();
list.add("csdn");

(2) Get data-get()

list.get(i);//i为集合的元素索引

(3) Delete data-remove()

list.remove(i);//i为集合的元素索引

(4) Get the collection length-size()

int l = list.size();
System.out.println("集合的长度是:"+l);

Second, a detailed introduction to the ArrayList collection

1. Define an ArrayList collection

(1) Grammar format

ArrayList<E> list = new ArrayList<>();

(2) Interpretation

  • <E>代表泛型, On behalf of the type loaded in the collection
  • 泛型只能是引用类型, Cannot be a basic type
  • For the ArrayList collection, it is 直接打印的结果not the address value, but 是内容if是空则打印 []
  • Starting from jdk1.7, it is not necessary to write content inside the right angle bracket

2. ArrayList collection commonly used methods

Define collection

Define an ArrayList collection of generic String

ArrayList<String> list = new ArrayList<>();
System.out.println(list);//打印结果为:[]

Add element

public boolean add (E e): add elements to the collection, the type is consistent with the generic

//只能添加字符串类型,其他类型会报错
list.add("CSDN");
list.add("aaaa");
list.add("bbbb");
System.out.println(list);
//打印集合结果为:[CSDN, aaaa, bbbb]

add方法有One can be seen through the ArrayList class 布尔类型的返回值, which can be used to return whether adding data is successful.

boolean res = list.add("ssss");
System.out.println("添加是否成功"+res);

For the ArrayList collection, using the add method will definitely add success (other collections may not), so the return value of the add method may not be used.

Get element

public E get(int index): Get the element from the collection, and the parameter index represents the element index number.

//获取集合的第 1 个元素
String strAdd = list.get(0);
System.out.println(Str);//结果为:CSDN
//根据添加顺序,第 0 号元素应为 “CSDN”

get方法有When one is defined with a collection 对应的泛型的返回值, the data type should be paid attention to when receiving data.

Delete element

public E remove(int index): Remove the element from the collection, the parameter index represents the element index number.

//删除集合的第 3 个元素
String strRemove = list.remove(2);
System.out.println("被删除的是:" + str);

remove方法有When a set is defined 对应的泛型的返回值, the data can be received after the delete operation is executed, and the deleted data can be viewed.

Get the collection length

public int size(): Get the collection length

int l = list.size();
System.out.println("集合的长度是:"+l);

3. Store the "class" in the ArrayList collection

(1) First define a standard class of Student

public class Student {
    
    
    private String name;
    private int age;
    public Person() {
    
    }
    public Person(String name, int age) {
    
    this.name = name;this.age = age;}
    public String getName() {
    
    return name;}
    public void setName(String name) {
    
    this.name = name;}
    public int getAge() {
    
    return age;}
    public void setAge(int age) {
    
    this.age = age;}
}

(2) Create a collection and store it in the "class"

import java.util.ArrayList;
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建集合
        ArrayList<Studentn> list = new ArrayList<>();
        //创建要存储的对象
        Student s1 = new Student("张三",17);
        Student s2 = new Student("李四",18);
        //将对象信息存入集合
        list.add(s1);
        list.add(s2);
        //使用匿名对象的方式存入也可以,因为这个对象只会被使用一次
        list.add(new Student("王五",19));
        //直接打印集合,会显示为对象的内存地址值
        System.out.println(list);
        //因此要想取出数据,必须再次创建对象接收数据
        Student p11 = list.get(0);
        System.out.println("姓名:"+p11.getName()+",年龄:"+p11.getAge());
    }

4. Traverse the ArrayList collection

import java.util.ArrayList;
/*
遍历ArrayList集合
 */
public class ArrayListEach {
    
    

    public static void main(String[] args) {
    
    
    	//创建集合对象
        ArrayList<String> list = new ArrayList<>();
        //添加数据
        list.add("aaaa");
        list.add("bbbb");
        list.add("cccc");
		//遍历集合
        for (int i = 0; i < list.size(); i++) {
    
    
            System.out.println(list.get(i));
        }
    }
    
}

5. Store the basic data types in the ArrayList collection

If you want to put a basic data type in the ArrayList collection, you must use the packaging class corresponding to the basic type.

The packaging classes corresponding to the basic types are as follows:

basic type Packaging classes (reference types, packaging classes are located in the java.lang package)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

【tips】
Except for the packaging types of int and char which are not capitalized, the other six basic types of packaging are capitalized.

import java.util.ArrayList;
public class ArrayListBasic {
    
    
    public static void main(String[] args) {
    
    
        //从jdk1.5开始可以自动装箱,自动拆箱
        //基本类型 --> 包装类型   装箱
        //包装类型 --> 基本类型   拆箱
        ArrayList<Integer> list = new ArrayList<>();
        list.add(100);
        list.add(200);
        list.add(300);
        //取出数据
        int num = list.get(1);
        System.out.println("取出的数据为:"+num);//结果为:取出的数据为:200
    }
}

6. ArrayList as a method parameter

case study:

1. ArrayList as a parameter
2. Use "{ }" as the opening and ending, and use "and" to separate each element

import java.util.ArrayList;
public class ArrayListParam {
    
    

    public static void main(String[] args) {
    
    
    	//创建集合
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        //System.out.println(list);
        //调用方法;并将创建的集合作为参数,传递给方法
        printArrayList(list);
    }
    
	//编写打印数组的方法,并将ArrayList集合设置为方法的参数
    public static void printArrayList(ArrayList list){
    
    
        System.out.print("{");
        for (int i = 0; i < list.size(); i++) {
    
    
            if(i == list.size()-1){
    
    
                System.out.print(list.get(i));
                System.out.print("}");
            }else {
    
    
                System.out.print(list.get(i)+"、");
            }
        }
    }
}

7. ArrayList as the return value of the method

case study:

1. Use the ArrayList collection as the return value of the method
2. Use a large collection to store 20 numbers, and filter the even numbers into a small collection

import java.util.ArrayList;
import java.util.Random;
public class ArrayListReturn {
    
    

    public static void main(String[] args) {
    
    
    
        ArrayList<Integer> list = returnArrayList();
        System.out.println(list);
    }
    
	//定义需求方法,并将返回值类型设置为ArrayList集合
    public static ArrayList<Integer> returnArrayList(){
    
    
        Random r = new Random();
        //定义大集合
        ArrayList<Integer> listBig = new ArrayList<>();
        //定义小集合
        ArrayList<Integer> listSmall = new ArrayList<>();
        
        for (int i = 0; i < 20; i++) {
    
    
            int num = r.nextInt(10);
            //向集合中添加数据
            listBig.add(num);
            //判断添加的数据是否为偶数,如果是,则将数据存入小集合
            if(listBig.get(i)%2 == 0){
    
    
                listSmall.add(listBig.get(i));
            }
        }
        System.out.println("偶数一共有:"+listSmall.size()+"个");
        //返回值为小集合
        return listSmall;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/105995822