日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

数据结构(Java)——迭代器和列表的实例

發(fā)布時間:2023/12/9 java 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构(Java)——迭代器和列表的实例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

感謝Java軟件結構與數(shù)據結構 John Lewis Joseph chase 著 金名譯

0. 迭代器關鍵概念(補充理解)

【1】迭代器是一個對象,它提供了一種依次訪問集合中每個元素的方式。
【2】經常把集合定義為Iterable的,說明需要時可以提供一個迭代器。
【3】迭代器可選方法remove使得它可以remove一個元素,而無需再遍歷集合。
【4】大多數(shù)迭代器是fail-fast的,當?shù)魅嗽谑褂弥畷r,如果修改集合,將拋出一個異常。
【5】不能假設迭代器訪問元素的順序,除非顯式聲明。
【6】迭代器往往實現(xiàn)為它所屬的集合的內部類。
【7】迭代器檢查修改技術,以確保與集合的修改計數(shù)保持一致。
【8】for-each循環(huán)只能夠用于實現(xiàn)了iterator接口的集合中,
【9】如果不是要處理集合中的所有元素或者如果要使用迭代器的remove方法,可以使用顯式迭代器而不是for-each循環(huán)。
【10】如果底層集合不是由迭代器本身進行修改的,fail-fast迭代器將快速而清晰地發(fā)生失敗。
【11】fail-fast的實現(xiàn):在后繼的操作中,迭代器會通知集合的修改計數(shù),確保該值不會被修改。如果改了,迭代器就會拋出ConcurrentModificationException異常。

2. Java集合API列表

Java集合API提供的列表類主要是支持索引列表。在一定程度上,這些類同無序列表是重疊的。JavaAPI中沒有實現(xiàn)事實上的有序列表。
【1】ArrayList是實現(xiàn)了基于動態(tài)數(shù)組的數(shù)據結構,LinkedList基于鏈表的數(shù)據結構。
【2】對于隨機訪問get和set,ArrayList覺得優(yōu)于LinkedList,因為LinkedList要移動指針。
【3】對于新增和刪除操作add和remove,LinedList比較占優(yōu)勢,因為ArrayList要移動數(shù)據。
ArrayList和LinkedList都實現(xiàn)了java.util.List接口。

3. 使用無序列表:學習計劃

Course.java

package ds.java.ch06;import java.io.Serializable;/** * @author LbZhang* @version 創(chuàng)建時間:2015年11月18日 上午10:19:57 * @description 類說明*/ public class Course implements Serializable{private String prefix;private int number;private String title;private String grade;public Course(String prefix, int number, String title, String grade) {super();this.prefix = prefix;this.number = number;this.title = title;if(grade==null){this.grade = "";}else{this.grade = grade;}}public Course(String prefix, int number, String title){this(prefix, number, title, "");}public String getPrefix() {return prefix;}public void setPrefix(String prefix) {this.prefix = prefix;}public int getNumber() {return number;}public void setNumber(int number) {this.number = number;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getGrade() {return grade;}public void setGrade(String grade) {this.grade = grade;}/*** Returns true if this course has been taken * * @return true if this course has been taken and false otherwise*/public boolean taken(){return !grade.equals("");}public boolean equals(Object other){boolean result = false;if (other instanceof Course){Course otherCourse = (Course) other;if (prefix.equals(otherCourse.getPrefix()) &&number == otherCourse.getNumber())result = true;}return result;}public String toString(){String result = prefix + " " + number + ": " + title;if (!grade.equals(""))result += " [" + grade + "]";return result;}}

ProgramOfStudy.java

package ds.java.ch06;import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List;/*** @author LbZhang* @version 創(chuàng)建時間:2015年11月17日 上午11:30:41* @description 類說明*/ public class ProgramOfStudy implements Iterable<Course>, Serializable {private List<Course> list;public ProgramOfStudy() {list = new LinkedList<Course>();}public void addCourse(Course course) {if (course != null)list.add(course);}public Course find(String prefix, int number) {for (Course course : list)if (prefix.equals(course.getPrefix())&& number == course.getNumber())return course;return null;}/*** 在某個元素之后添加元素* @param target* @param newCourse*/public void addCourseAfter(Course target, Course newCourse) {if (target == null || newCourse == null)return;int targetIndex = list.indexOf(target);//獲取索引if (targetIndex != -1)list.add(targetIndex + 1, newCourse);}public void replace(Course target, Course newCourse) {if (target == null || newCourse == null)return;int targetIndex = list.indexOf(target);if (targetIndex != -1)list.set(targetIndex, newCourse);}public String toString() {String result = "";for (Course course : list)result += course + "\n";return result;}public Iterator<Course> iterator() {return list.iterator();}public void save(String fileName) throws IOException {FileOutputStream fos = new FileOutputStream(fileName);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(this);oos.flush();oos.close();}public static ProgramOfStudy load(String fileName) throws IOException,ClassNotFoundException {FileInputStream fis = new FileInputStream(fileName);ObjectInputStream ois = new ObjectInputStream(fis);ProgramOfStudy pos = (ProgramOfStudy) ois.readObject();System.out.println(pos);ois.close();return pos;}}

POSTester.java

package ds.java.ch06; import java.io.IOException;/*** @author LbZhang* @version 創(chuàng)建時間:2015年11月18日 上午9:46:48* @description 類說明*/ public class POSTester {public static void main(String[] args) throws IOException,ClassNotFoundException {ProgramOfStudy pos = new ProgramOfStudy();pos.addCourse(new Course("CS", 101, "Introduction to Programming", "A-"));pos.addCourse(new Course("ARCH", 305, "Building Analysis", "A"));pos.addCourse(new Course("GER", 210, "Intermediate German"));pos.addCourse(new Course("CS", 320, "Computer Architecture"));pos.addCourse(new Course("THE", 201, "The Theatre Experience"));Course arch = pos.find("CS", 320);pos.addCourseAfter(arch, new Course("CS", 321, "Operating Systems"));Course theatre = pos.find("THE", 201);theatre.setGrade("A-");Course german = pos.find("GER", 210);pos.replace(german, new Course("FRE", 110, "Beginning French", "B+"));System.out.println(pos);pos.save("ProgramOfStudy"); // pos = pos.load("ProgramOfStudy"); // System.out.println(pos);}}

4. 約瑟夫問題

4.1 索引列表實現(xiàn)

package ds.java.ch06;import java.util.ArrayList; import java.util.List; import java.util.Scanner;/*** @author LbZhang* @version 創(chuàng)建時間:2015年11月18日 上午11:18:20* @description 約瑟夫問題* */ public class Josephus {public static void main(String[] args) {int numPeople, skip, targetIndex;List<String> list = new ArrayList<String>();Scanner in = new Scanner(System.in);// get the initial number of soldiersSystem.out.print("Enter the number of soldiers: ");numPeople = in.nextInt();in.nextLine();// get the number of soldiers to skipSystem.out.print("Enter the number of soldiers to skip: ");skip = in.nextInt();if(numPeople<skip){System.out.println("**不能進行約瑟夫環(huán)**");return ;}// load the initial list of soldiersfor (int count = 1; count <= numPeople; count++) {list.add("Soldier " + count);}//now location indextargetIndex = skip;System.out.println("The order is: ");// Treating the list as circular, remove every nth element// until the list is emptywhile (list.size()>2) {System.out.println(list.remove(targetIndex));if (list.size() > 0)targetIndex = (targetIndex + skip) % list.size();}System.out.println(list);}}

4.2 數(shù)組實現(xiàn)

package ds.java.ch06;import java.util.Scanner;/*** @author LbZhang* @version 創(chuàng)建時間:2015年11月18日 下午12:23:55* @description 類說明*/ public class MyJosephus {private int total;// 總人數(shù)private int numCount;// 從當前開始第幾個出列private int beginNum;// 開始編號private int[] solider;// 士兵隊列private int[] outSequence;// 出隊次序public MyJosephus(int total, int numCount, int beginNum) {super();this.total = total;this.numCount = numCount;this.beginNum = beginNum;this.solider = new int[total];// 初始化for (int i = 0; i < solider.length; i++) {solider[i] = i;}this.outSequence = new int[total];}public void exec() {int counter = 0;// /標價變量int i = this.beginNum;int j = 0;int killperson = 0;while (true) {if (solider[i] != -1) {// pserson[i]的值是-1,代表出環(huán)// 沒有出環(huán),計數(shù)器加1counter++;// 判定是否數(shù)目達到numCountif ((counter) % numCount == 0) {outSequence[j++] = i + 1;// 填入隊列killperson++;solider[i] = -1;// 殺死當前編號士兵}}i = (i + 1) % total;// 向后遍歷if (killperson == total) {break;}}System.out.println("出環(huán)按順序為:");for (int k = 0; k < outSequence.length; k++) {// 輸出出環(huán)順序System.out.print(outSequence[k] + " ");}}public static void main(String[] args) {int total = 0;int numCount = 0;int begin = 0;Scanner scn = new Scanner(System.in);while (true) {System.out.println("Input total num:");total = scn.nextInt();System.out.println("Input numCount:");numCount = scn.nextInt();System.out.println("Input begin:");begin = scn.nextInt();if (total != 0 && numCount != 0 && total > numCount) {MyJosephus mj = new MyJosephus(total, numCount, begin);mj.exec();break;} else {System.out.println("您輸入的數(shù)據不合理,請重試!");}}}}

輸出結果:

轉載于:https://www.cnblogs.com/mrzhang123/p/5365834.html

總結

以上是生活随笔為你收集整理的数据结构(Java)——迭代器和列表的实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。