public class Student{ private String id; private String name; private String age; public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Student(){} public Student(String id,String name,String age){ this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "学号=" + id + ", 名字=" + name + ", 年龄=" + age; } public static Student fromString(String s){ String[] split = s.split(";"); if(split.length==3){ return new Student(split[0],split[1],split[2]); }else{ throw new RuntimeException("不能从字符串‘"+s+"’解析出"+Student.class+"类型的对象!"); } } } //Iterators.java package shiyan18; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public class Iterators { public static void main(String[] args) { InputStream is = Iterators.class.getClassLoader().getResourceAsStream("shiyan18/Student.txt"); List<Student> list = getStudents(is); System.err.println("学号从小到大:"); Iterator<Student> iterator = list.iterator(); while(iterator.hasNext()){ Student student = iterator.next(); System.out.println(student); } System.err.println("学号从大到小:"); ListIterator<Student> li=list.listIterator(); for(li=list.listIterator();li.hasNext();) { li.next(); } for(;li.hasPrevious();) { Student student = li.previous(); System.out.println(student); } } private static List<Student> getStudents(InputStream is){ List<Student> list = new LinkedList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String temp = null; try { while((temp=reader.readLine())!=null){ Student student = Student.fromString(temp); list.add(student); } } catch (IOException e) { e.printStackTrace(); } return list; } }
标签:总结,23.11,java,String,18,id,Student,public,name From: https://www.cnblogs.com/laobing6214/p/17843181.html