學生日誌管理系統(ArrayList集合的應用)
前幾天學了集合框架,現在先大致對集合總結一下,再對ArrayList的一個例項進行具體講解。
所有集合的上層介面為collection介面,它有三個子介面,分別為List,Set,Map。
其中,List介面的實現類均是線性結構,其中儲存的元素是有序的,主要有三個常用的,分別是ArrayList,Vector,LinkedList,其中,前兩個是線性表,便於查詢,後一個是線性連結串列,便於對元素進行增刪改操作
Set集合中不允許重複的元素存在,集合中元素的存放是無序的,常用的實現類有HashSet,TreeSet
Map集合中的元素是以鍵值對<key,value>的形式存在的,一個鍵對應一個值,集合中不允許重複的鍵,常用的實現類有HashMap和TreeMap,其中,前者不允許存在空值和空鍵
List集合中的ArrayList:相當於一個動態陣列,陣列的容量隨著新增物件的增加而不斷動態擴充套件,當容量不夠時,容量擴充套件至原來的1.5倍,其實現是執行緒不同步的。
為了進一步對ArrayList進行深入的理解,下面介紹一個小專案,一個簡單的學生日誌管理系統,其主要實現為
1、學生資訊管理:實現學生的登入,註冊功能
2、學生日誌管理:實現對學生日誌增刪改查功能
要對學生物件和學生日誌進行管理,則首先要建立一個學生物件和日誌物件(為圖簡便,將日誌物件簡化為了字串,實際學生和日誌應為一對多的依賴關係):
public class Student { int sno; String password; ArrayList<String> dinary=new ArrayList<String>(); public Student(){}; public Student(int sno, String password) { super(); this.sno = sno; this.password = password; } public Student(int sno, String password, ArrayList<String> dinary) { super(); this.sno = sno; this.password = password; this.dinary = dinary; } }
接下來,要實現學生物件的登入註冊功能,登入時,首先判斷是否已註冊,已註冊的學生資訊和將要註冊的學生資訊均放入動態陣列ArrayList<Student>中臨時儲存,若還未註冊,則要先註冊,才能進行登入。
即登入時,首先判斷學生輸入的賬號是否存在,若存在,則再驗證其密碼是否正確,若不存在,則給出提示其賬號不存在,可先註冊再登陸。
若登入成功,則用一個索引來記錄當前登入的學生物件在儲存其資訊的容器ArrayList中的索引,以便於對當前登入的學生物件的資訊進行管理。登入成功後,才可對當前學生物件的日誌進行管理。
public class StudentManage { int index=-1; ArrayList<Student> db=new ArrayList<Student>(); private Scanner s(){ return new Scanner(System.in); } public void loagn(){ System.out.println("請輸入賬號:"); Scanner sc=s(); int ID=sc.nextInt(); for (int i = 0; i < db.size(); i++) { if(ID==db.get(i).sno){ index=i; break; } } if(index==-1){ System.out.println("此賬號未註冊!"); System.out.println("重新輸入賬號請按 1,註冊賬戶請按 2:"); if(sc.nextInt()==1) loagn(); else if(sc.nextInt()==2){ addStudent(); loadMenue(); } else System.exit(0); }else checkCode(); } private void checkCode(){ System.out.println("請輸入密碼:"); Scanner sc=s(); String code=sc.nextLine(); if(code.equals(db.get(index).password)){ System.out.println("登入成功!"); DinaryManage(); }else{ System.out.println("密碼錯誤!"); checkCode(); } } public void addStudent(){ System.out.println("請按格式輸入註冊資訊:學號\t密碼"); Scanner sc=s(); int no=sc.nextInt(); String code=sc.nextLine(); Student e=new Student(no,code); db.add(e); } public void loadMenue2(){ System.out.println("新增日誌請按 1,刪除日誌請按 2:"); Scanner sc=s(); int se=sc.nextInt(); if(se==1){ System.out.println("請輸入要寫的日誌內容:"); String line=sc.nextLine(); String content=line; if(line!=null){ line=sc.nextLine(); content=content+line; } db.get(index).dinary.add(content); loadMenue2(); }else if(se==2){ System.out.println("請輸入要刪除的日誌的序號:"); se=sc.nextInt(); db.get(index).dinary.remove(se); }else System.exit(0); } private void DinaryManage(){ loadMenue2(); } public static void main(String[] args) { StudentManage SM=new StudentManage(); SM.loadMenue(); } private void loadMenue() { System.out.println("登入請按 1,註冊請按 2:"); Scanner sc=s(); int select=sc.nextInt(); if(select==1) loagn(); else if(select==2){ addStudent(); loadMenue(); } else System.exit(0); } }