ArrayList

  • 集合的概念:
  • 集合是一个容器,是一个载体,一次可以容纳多个对象
  • 相比之前的数组,数组必须规定大小,集合可以不确定
  • 集合储存的是什么?
    • 集合不能直接存储基本的数据类型
    • 集合也不能直接存储对象
    • 集合中储存的是对象在内存中的地址(或者叫做引用)
    • 集合本身也是一个对象
  • 集合的数据结构:
    • 不同的集合,底层对应不同的数据结构。向不同的集合中存储数据,等于向不同的数据结构存储数据。
    • 数据结构:数据的存储方式。(数组、链表、树、哈希表、图等)
    • Collection:以单个元素形式储存
    • Map:以键值对形式储存

1
2
3
4
5
6
7
8
9
10
11
public class Sutdent {
privite int age;
privite String name;
public Student (int age, String name) {
this.age = age;
this.name = name;
}
public static getName() {
System.out.print("我是" + this.name)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.ArrayList;
public class ArrayList01 {
public static void main(String[] args) {
Student s1 = new Student(10, "张三");
Student s2 = new Student(11, "李四");
Student s3 = new Student(12, "王五");

// 创建一个对象
ArrayList<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
list.size(); // 3
list.remove(0);
list.size(); // 2
list.get(0).getName(); // 我是李四
}

// 储存基本的数据类型
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(1);
list2.add(2);
list2.add(3);
}

异常处理

错误上抛处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Scanner;
public class Exception01 {
public static void main(String[] args) {
try {
doSome();
} catch (Exception e) {
System.out.printLn("您输入的不是一个整数");
}
}
public static void doSome() throws Exception {
Scanner sc = new Scanner(System.in);
System.out.printIn("请输入一个整数:");
int a = sc.nextInt();
}
}

错误自己处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
public class Exception01 {
public static void main(String[] args) {
try {
doSome();
} catch (Exception e) {
System.out.printLn("您输入的不是一个整数");
}
}
public static void doSome() {
Scanner sc = new Scanner(System.in);
System.out.printIn("请输入一个整数:");
try {
int a = sc.nextInt();
} catch (Exception e) {
System.out.printLn("您输入的不是一个整数");
}
}
}