一.增删改查
public static void main(String[] args) {
// 1. 集合创建
ArrayList<String> list = new ArrayList<>(); // 泛型指定存储类型
System.out.println(list); // 输出空列表:[]
// 2. 增删操作
// 添加元素(返回操作结果)
list.add("1");
boolean result = list.add("1"); // 添加成功返回true
// 删除元素(两种方式)
list.remove(1); // 按索引删除(返回被删元素)
list.remove("1"); // 按内容删除(返回boolean)
boolean str = list.remove("1"); // 删除成功返回true
list.clear(); // 清空集合
// 3. 修改操作
list.set(0, "3"); // 修改指定索引元素
// 4. 查询操作
String s = list.get(0); // 获取指定索引元素
int size = list.size(); // 获取集合长度
// 5. 遍历方式
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
二.数组与集合的区别
-
数组长度固定,集合长度可变
-
数组可存基本类型,集合只能存引用类型
-
若集合使用基本数据类型,需要变为包装类,除了char-character,int-integer,其他都是大写字母第一个
三.引用数据类型的应用
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Student s1 = new Student("张三", 12);
Student s2 = new Student("李四", 13);
Student s3 = new Student("王五", 14);
list.add(s1);
list.add(s2);
list.add(s3);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName() + "," + list.get(i).getAge());
}
for (int i = 0; i < 3; i++) {
Student s = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("输入学生姓名:");
String name = sc.nextLine();
System.out.println("输入学生年龄");
int age = sc.nextInt();
s.setName(name);
s.setAge(age);
list.add(s);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName() + "," + list.get(i).getAge());
}
}