[Learning] Java ArrayList collection

ArratList

The difference between the array and
the array length may not change
, but the length can be set arbitrarily changed ArrayList.

ArrayList, there is a sharp brackets <...> represents the generic
generic : that is, the set of all elements contained in them, and what types are all unified.

ArrayList<int> list = new ArrayList<>();        //错误写法
ArrayList<Integer> list = new ArrayList<>(); 

Note: Generics can only be a reference type, not a basic type

basic type Reference types
byte Byte
int Integer
long Long
short Short
float Float
double Double
char Character
boolean Boolean

Note:
For ArrayList set, the address value is not obtained direct printing, but the content
if the content is empty, empty is obtained in parentheses: []

Common method

集合名称.add(); //向集合中添加元素,类型与泛型一致
集合名称.get(); //从集合中获取元素,参数是索引编号,返回值是对应位置的元素
集合名称.remove(); //从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素

Exercises

Generating a random integer between 1 and 6 to 33, added to the collection, through the collection

import java.util.ArrayList;
import java.util.Random;
public class Demo01ArrayListRandom {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        Random r = new Random();

        for (int i = 0; i < 6; i++) {
            int num = r.nextInt(33) + 1;
            list.add(num);
        }
        // 遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

Exercise 2

With a large collection of random numbers is stored in 20, and then screened for the even elements, set into small

import java.util.ArrayList;
import java.util.Random;
public class Demo04ArrayListReturn {
    public static void main(String[] args) {
        ArrayList<Integer> bigList = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 20; i++) {
            int num = r.nextInt(100) + 1;
            bigList.add(num);
        }
        // 创建一个集合来接收返回的偶数   
        //  【学习中的错误,直接调用方法】
        ArrayList<Integer> smallList = getSmallList(bigList);
        System.out.println("总共有" + smallList.size());
        for (int i = 0; i < smallList.size(); i++) {
            System.out.println(smallList.get(i));
        }
    }
    // 可以用集合作为返回值类型,将bigList中的值作为参数传入
    //将其中的偶数放到smallList中返回
    public static ArrayList<Integer> getSmallList(ArrayList<Integer> bigList){
        ArrayList<Integer> smallList = new ArrayList<>();
        for (int i = 0; i < bigList.size(); i++) {
            int num = bigList.get(i);
            if (num % 2 == 0){
                smallList.add(num);
            }
        }
        return smallList;
    }
}
Released seven original articles · won praise 2 · Views 265

Guess you like

Origin blog.csdn.net/sy140823/article/details/104564348