1.ArrayList
集合和数组的优势对比:
- 长度可变
- 添加数据的时候不需要考虑索引,默认将数据添加到末尾
1.1 ArrayList类概述
1.2 ArrayList类常用方法
1.2.1 构造方法
| 方法名 |
说明 |
| public ArrayList() |
创建一个空的集合对象 |
格式:ArrayList<E> array = new ArrayList<E>();
1.2.2 成员方法
| 方法名 |
说明 |
| public boolean add(要添加的元素) |
将指定的元素追加到此集合的末尾 |
| public boolean remove(要删除的元素) |
删除指定元素,返回值表示是否删除成功 |
| public E remove(int index) |
删除指定索引处的元素,返回被删除的元素 |
| public E set(int index,E element) |
修改指定索引处的元素,返回被修改的元素 |
| public E get(int index) |
返回指定索引处的元素 |
| public int size() |
返回集合中的元素的个数 |
1.2.3 示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class ArrayListDemo02 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>();
array.add("hello"); array.add("world"); array.add("java");
array.remove("world")); array.remove("javaee"));
array.remove(1);
array.remove(3);
array.set(1,"javaee");
array.set(3,"javaee");
array.get(0); array.get(1); array.get(2);
array.size();
System.out.println("array:" + array); } }
|
1.3 ArrayList遍历
1 2 3 4 5 6
|
for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
|
1.4 基本数据类型对应的包装类
byte Byte
shot Short
char Char
int Interger
long Long
float Float
double Double
boolean Boolean
1.5 添加对象
需求:
1,main方法中定义一个集合,存入三个用户对象。
用户属性为:id,username,password
2,要求:定义一个方法,根据id查找对应的学生信息。
如果存在,返回索引
如果不存在,返回-1
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public class ArrayListDemo6 { public static void main(String[] args) {
ArrayList<User> list = new ArrayList<>();
User u1 = new User("heima001", "zhangsan", "123456"); User u2 = new User("heima002", "lisi", "1234"); User u3 = new User("heima003", "wangwu", "1234qwer");
list.add(u1); list.add(u2); list.add(u3);
int index = getIndex(list, "heima001");
System.out.println(index);
}
public static int getIndex(ArrayList<User> list, String id) { for (int i = 0; i < list.size(); i++) { User u = list.get(i); String uid = u.getId(); if(uid.equals(id)){ return i; } } return -1; } }
|
1.6 判断用户的是否存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public class ArrayListDemo5 { public static void main(String[] args) {
ArrayList<User> list = new ArrayList<>();
User u1 = new User("heima001","zhangsan","123456"); User u2 = new User("heima002","lisi","12345678"); User u3 = new User("heima003","wangwu","1234qwer");
list.add(u1); list.add(u2); list.add(u3);
boolean result = contains(list, "heima001"); System.out.println(result);
}
public static boolean contains(ArrayList<User> list, String id){
for (int i = 0; i < list.size(); i++) { User u = list.get(i); String uid = u.getId(); if(id.equals(uid)){ return true; } } return false; }
}
|