1. 程式人生 > 其它 >LinkedList-----普通for迴圈、增強for迴圈、迭代器的運用

LinkedList-----普通for迴圈、增強for迴圈、迭代器的運用

2.設計一個Student類,該類中包括學生的姓名和成績。建立Student類的5個物件,

將以上5個物件放入LinkedList中,如圖:

name

scroe
劉德華 85
張學友 100
王傑 65
章子怡 58
周迅 76

完成如下操作和統計:

1、輸出LinkedList中的物件個數。

2、刪除姓名為“劉傑”的學生資訊,並輸出LinkedList中現有學生資訊。

3、將姓名為“劉德華”的學生成績改為95。

4、輸出成績不及格的學生姓名

public class Student {
private String name;
private int scroe;



public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getscroe() {
return scroe;
}
public void setscroe(int scroe) {
this.scroe = scroe;
}




public Student(String name, int scroe) {
super();
this.name = name;
this.scroe = scroe;
}
public Student() {
super();
}



@Override
public String toString() {
return "Student [name=" + name + ", scroe=" + scroe + "]";
}

//三種方法每次執行一種

mport java.util.Iterator;
import java.util.LinkedList;

public class TestLinkeList {
public static void main(String[] args) {
LinkedList<Student> ll=new LinkedList<Student>();
ll.add(new Student("劉德華",85));
ll.add(new Student("張學友",100));
ll.add(new Student("王傑",65));
ll.add(new Student("章子怡",58));
ll.add(new Student("周迅",76));
System.out.println(ll.size()); //獲取集合大小


//ll.clear();//刪除集合元素


//------=====--------------------------------------------------------
//普通for迴圈-------------------------
for(int i=0;i<ll.size();i++) {
Student s=ll.get(i);
if(s.getName().equals("王傑")) {//刪除姓名為“劉傑”的學生資訊,並輸出LinkedList中現有學生資訊。
//ll.remove(i);//隱式呼叫equals比較
ll.remove(s);//同上
i--;//*******



}
if(s.getName().equals("劉德華")) {//將姓名為“劉德華”的學生成績改為95。
s.setscroe(95);

}

if(s.getscroe()<60) {//輸出成績不及格的學生姓名
System.out.println(s);
}
}
System.out.println(ll);


//-------------------------------------------------------------------------

//增強for迴圈-----不能刪除----不能對陣列進行修改-------------
for(Student s:ll) {
if(s.getName().equals("劉德華")) {
s.setscroe(95);//將姓名為“劉德華”的學生成績改為95。
}
if(s.getscroe()<60) {
System.out.println(s);//輸出成績不及格的學生姓名

}

}
System.out.println(ll);


//-------------------------------------------------------------------------


//迭代器
Iterator<Student> ite=ll.iterator();
while(ite.hasNext()){
Student s=ite.next();
if(s.getName().equals("王傑")) {//刪除姓名為“劉傑”的學生資訊,並輸出LinkedList中現有學生資訊
ite.remove();
}
if(s.getName().equals("劉德華")) {//將姓名為“劉德華”的學生成績改為95。

s.setscroe(95);
}
if(s.getscroe()<60) {
System.out.println(s);//輸出成績不及格的學生姓名
}
}
System.out.println(ll);
}
}