首先创建一个student类,创建实例对象最好用 private 修饰,在编写一个无参构造,在重写三个实例变量的 toString 方法,equals 方法, get ,set 方法;
package 实例;
public class student {
private String stuno;
private String name;
private int score;
public student() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + score;
result = prime * result + ((stuno == null) ? 0 : stuno.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
student other = (student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (score != other.score)
return false;
if (stuno == null) {
if (other.stuno != null)
return false;
} else if (!stuno.equals(other.stuno))
return false;
return true;
}
@Override
public String toString() {
return "student [stuno=" + stuno + ", name=" + name + ", score=" + score + "]";
}
public String getStuno() {
return stuno;
}
public void setStuno(String stuno) {
this.stuno = stuno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
在编写一个测试类,使用前面学到的操作方法来进行操作
package 实例;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class test {
public static void main(String[] args) {
String text="01,勇哥,100;02,王哥,10;03,白哥,90;04,李哥,50;06,是的哥,100;";
//1)把字符串中的学生信息分离出来;
String[] words=text.split("[,;]");
//2)创建List集合,根据分离出来的学生信息创建学生对象,添加到List集合中
List<student> list=new ArrayList<>();
//遍历w数组中的内容,创建student对象,保存到list集合中
for(int i=0;i<words.length;i+=3) {
student stu=new student();
stu.setStuno(words[i]);
stu.setName(words[i+1]);
stu.setScore(Integer.parseInt(words[i+2]));
list.add(stu);
}
//3)通过迭代分别打印集合中的学生信息
Iterator<student> iterator = list.iterator();
while (iterator.hasNext()) {
student student = (student) iterator.next();
System.out.println(student);
}
//4)判断集合中是否存在姓名为"明哥"的同学
boolean mingge=false;
for (student student : list) {
if("明哥".equals(student.getName())) {
mingge=true;
break;
}
}
if(mingge) {
System.out.println("有");
}else {
System.out.println("没有");
}
//5)对集合中的学生按成绩降序排序
list.sort(new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
// TODO Auto-generated method stub
return o2.getScore()-o1.getScore();
}
});
//通过循环打印集合中学生的信息
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
//7)删除姓名为"勇哥"的学生
iterator = list.iterator();
while (iterator.hasNext()) {
student student = (student) iterator.next();
if("勇哥".equals(student.getName())) {
iterator.remove();
}
}
//使用foreach循环打印
System.out.println();
for (student student : list) {
System.out.println(student);
}
}
}