Generally, elements cannot be added to an array, because the length of the array has been determined when it is initialized, and the length cannot be changed.
How to dynamically increase array elements?
use ArrayList<type> list = new ArrayList<>();
1. Definition
However, the type cannot be a basic type, such as the following error will be reported
ArrayList<int> list = new ArrayList<>();
must be the following
ArrayList<Integer> list = new ArrayList<>();
If you want to store basic data types in ArrayList, you must use the "wrapper class" corresponding to the basic data types.
basic type | Packaging class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
2. Adding elements
ArrayList<Integer> list = new ArrayList<>();
list.add(100);
list.add(101); //添加元素
System.out.println(list);
If you want to add an element at any position, you can specify the addition position, as shown in the figure, the code adds the element to the position of the array index 0.
list.add(0, 200);
list.add(2, 102);
System.out.println(list);
3. Take out elements
int var = list.get(1); //取出元素
Fourth, delete elements
The remove() method is used to remove a single element from a dynamic array.
The syntax of the remove() method is:
// delete the specified element arraylist.remove(Object obj) // delete the element at the specified index position arraylist.remove(int index)
Note: arraylist is an object of class ArrayList.
Parameter Description:
- obj - the element to remove
- index - the index value of the element to delete
If the obj element appears multiple times, the first occurrence of the element in the dynamic array is removed.
list.remove(1);
System.out.println(list);
list.remove(Integer.valueOf(102));
System.out.println(list);
Note the difference between interger and int
5. Complete code
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(100);
list.add(101); //添加元素
System.out.println(list);
list.add(0, 200);
list.add(2, 102);
System.out.println(list);
System.out.println(list.get(1));
list.remove(1);
System.out.println(list);
// list.remove(102);
// System.out.println(list);
list.remove(Integer.valueOf(102));
System.out.println(list);
}
}
reference
How to add elements to an array in Java - Programmer Sought
[Java Notes] ArrayList of java stores basic data types - XieCangfeng - Blog Park
Java ArrayList remove() method | Beginner Tutorial
Attacking the public account: Microprogram School