Java中運用ArrayList和不用ArrayList的區別——存盤學生物件并遍歷
- 簡單介紹
- 題目要求
- 研究代碼
- Student.java
- MyArrayList.java
簡單介紹
- 什么是集合
提供一種存盤空間可變的存盤模型,存盤的資料容量可以發生改變 - ArrayList集合的特點
底層是陣列實作的,長度可以變化 - 泛型的使用
用于約束集合中存盤元素的資料型別
題目要求
創建一個存盤學生物件的集合,存盤3個學生物件,使用程式實作在控制臺遍歷該集合
學生的姓名和年齡來自于鍵盤錄入
研究代碼
Student.java
首先是寫一個Student的類,后面用
package study01;
public class Student {
private String name;
private String age;
public Student() {
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(String age) {
this.age = age;
}
public String getAge() {
return age;
}
}
MyArrayList.java
下面用了3種不同的方法進行比較,便于我們理解,有興趣的同學可以看看:
package study01;
import java.util.ArrayList;
import java.util.Scanner;
public class MyArrayList {
public static void main(String[] args) {
//1.普通方法
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("請輸入學生姓名:");
s1.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s1.setAge(sc.nextLine());
System.out.println("請輸入學生姓名:");
s2.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s2.setAge(sc.nextLine());
System.out.println("請輸入學生姓名:");
s3.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s3.setAge(sc.nextLine());
System.out.println(s1.getName() + " " + s1.getAge());
System.out.println(s2.getName() + " " + s2.getAge());
System.out.println(s3.getName() + " " + s3.getAge());
//2.運用ArrayList
ArrayList<Student> array = new ArrayList<Student>();
// Student s1 = new Student();
// Student s2 = new Student();
// Student s3 = new Student();
// Scanner sc = new Scanner(System.in);
System.out.println("請輸入學生姓名:");
s1.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s1.setAge(sc.nextLine());
System.out.println("請輸入學生姓名:");
s2.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s2.setAge(sc.nextLine());
System.out.println("請輸入學生姓名:");
s3.setName(sc.nextLine());
System.out.println("請輸入學生年齡:");
s3.setAge(sc.nextLine());
array.add(s1);
array.add(s2);
array.add(s3);
for (int i = 0; i < array.size(); i++) {
Student s = array.get(i);
System.out.println(s.getName() + "," + s.getAge());
}
//3.高效的ArrayList方法
ArrayList<Student> array1 = new ArrayList<Student>();
for (int i = 0; i < 3; i++) {
addStudent(array1);
}
for (int i = 0; i < array1.size(); i++) {
Student st2 = array1.get(i);
System.out.println(st2.getName() + " " + st2.getAge());
}
}
//這個方法是定義在(3.高效的ArrayList方法)后面的
public static void addStudent(ArrayList<Student> array1) {
Scanner sc1 = new Scanner(System.in);
System.out.println("請輸入學生姓名:");
String name = sc1.nextLine();
System.out.println("請輸入學生年齡:");
String age = sc1.nextLine();
Student st1 = new Student();
st1.setName(name);
st1.setAge(age);
array1.add(st1);
}
}
下面給出運行的結果:


如果對您有幫助的話,不妨點個贊支持一下唄!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/44693.html
標籤:其他
