集合问题
在集合中,如何删除集合中的单个元素和全部元素
我只会添加,不回删除,各位兄弟帮帮忙!
package bao4;
//Student类实现接口Comparable,
//然而这个接口有一个参数是对象类型的StudentOne
public class StudentOne implements Comparable<StudentOne>{
public String name;//成员变量名字
public int age;//成员变量年龄
public String id;//成员变量学号
//空构造方法
public StudentOne(){
}
//带参构造方法用于初始化的时候传递参数
public StudentOne(String id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public String getId(){
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
//按照id进行排序
public int compareTo(StudentOne o) {
//这里的id或者name是String类型
return id.compareTo(o.id);
//return name.compareTo(o.name);
}
//返回一个类构造方法的所有属性,也可以返回一部分
public String toString(){
return id+" "+name+" "+age;
}
}
package bao4;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class StudentOneText {
//给集合添加一个参数Student,说明在这个 l 集合中只能添加Student类型的元素
LinkedList<StudentOne> l=new LinkedList<StudentOne>();
//给集合添加一个参数Integer,说明在这个 a 集合中只能添加Integer类型的元素
LinkedList<Integer> a=new LinkedList<Integer>();
public void say1(){
//给集合 a 中添加Integer类型的元素
a.add(new Integer(2));
a.add(new Integer(7));
a.add(new Integer(4));
a.add(new Integer(3));
a.add(new Integer(6));
a.add(new Integer(5));
System.out.println(a);
System.out.println("-----------------------------");
Collections.sort(a);//通过Collections的sort方法排序
//输出集合中的各个元素
System.out.println(a);
}
public void say(){
//添加Student类型的元素在 l 中
l.add(new StudentOne("3","许遥遥",26));
l.add(new StudentOne("2","柴金栋",25));
l.add(new StudentOne("1","许晓铎",28));
l.add(new StudentOne("9","吴洋洋",23));
l.add(new StudentOne("7","周春华",27));
l.add(new StudentOne("6","吴彬彬",24));
l.add(new StudentOne("5","胡莎",23));
System.out.println(l);
System.out.println("---------------------------------------------------------------------------------");
Collections.sort(l);//通过Collections的sort方法排序
System.out.println(l);
System.out.println("*********************************************************************************");
Namea sayy=new Namea();
Collections.sort(l,sayy);//通过Collections的sort方法排序
System.out.println(l);
}
public void like(){
StudentText n=new StudentText();
n.notifyAll();
}
public static void main(String[] args) {
StudentText na=new StudentText();
na.say();
na.say1();
}
}
class Namea implements Comparator<StudentOne>{
public int compare(StudentOne ab,StudentOne ba){
return ab.name.compareTo(ba.name);
}
}