(JAVA高階特性)第一章 集合框架
阿新 • • 發佈:2019-02-02
1,建立一個類Queue,代表隊列(特點:先進先出),新增add(Object obj)及get()方法,mian()方法驗證。
2,建立一個HashMap類,新增學員姓名及分數,鍵為學生姓名,值為分數。從HashMap物件獲取並輸出,修改一位同學的成績,再次輸出。package com.bdqn.demo; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; public class Queue { private List<Object> arrayList = new ArrayList<Object>(); private LinkedList<Object> linkedList = new LinkedList<Object>(); //ArrayList實現的先進先出 public void arrayListAdd(Object obj) { this.arrayList.add(obj); } public Object arrayListGet() { Object obj = null; if (this.arrayList.size() > 0) { obj = this.arrayList.get(0); this.arrayList.remove(0); } return obj; } //LinkedList實現的先進先出 public void linkedListAdd(Object obj) { this.linkedList.addFirst(obj); } @SuppressWarnings("finally") public Object linkedListGet(){ Object obj = null; try { obj = this.linkedList.getLast(); this.linkedList.removeLast(); } catch (NoSuchElementException e) { }finally{ return obj; } } public static void main(String[] args) { Queue queue = new Queue(); //測試ArrayList,新增0 1 2進去 for (int i = 0; i < 3; i++){ System.out.println("arrayListAdd("+i+")"); queue.arrayListAdd(i); } //輸出4次,第4次應該為null,輸出順序和放入順序一致 for (int i = 0; i < 4; i++) { System.out.println("arrayListGet()=="+queue.arrayListGet()); } //測試Linkedlist,新增0 1 2進去 for (int i = 0; i < 3; i++){ System.out.println("linkedListAdd("+i+")"); queue.linkedListAdd(i); } //輸出4次,第4次應該為null,輸出順序和放入順序一致 for (int i = 0; i < 4; i++) { System.out.println("linkedListGet()=="+queue.linkedListGet()); } } }
package com.bdqn.demo; public class Student { private String name;//學生姓名 private int score;//分數 public Student( String name,int score) {//過載接收引數 this.name=name; this.score=score; } public String getName() {//獲取名字 return name; } public int getScore() {//獲取分數 return score; } } package com.bdqn.demo; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; //測試類 public class Test { public static void main(String[] args) { //學生引數傳遞 Student stu1=new Student("張三", 99); Student stu2=new Student("李四", 80); Student stu3=new Student("王五", 86); Student stu4=new Student("趙六", 72); Map <String,Student>score=new HashMap<String,Student>();//宣告HashMap //新增學生引數集合 score.put(stu1.getName(),stu1); score.put(stu2.getName(),stu2); score.put(stu3.getName(),stu3); score.put(stu4.getName(),stu4); for(String key:score.keySet()) {//foreach列印 System.out.println(key+"\t"+score.get(key).getScore()); } stu4=new Student("趙六",76);//修改一名學生成績 score.put(stu4.getName(), stu4);//新增修改的資料 System.out.println("修改後的學員成績如下:");//列印修改後的學生成績 for(String key:score.keySet()) { System.out.println(key+"\t"+score.get(key).getScore()); } } }