List<student>包含10个student对象,student对象里面有个年龄的属性,遍历List<student>,找出年龄最大的对象,将该对象的一个属性设置为True.
JAVA基础
------解决方案--------------------
1.循环比较
2.写个比较器根据年龄排序,倒序就是第一个,顺序就是最后一个
------解决方案--------------------
package test01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Student implements Comparable<Student>{
private String name;
private int age;
private boolean GoodStu;
public Student(String name, int age, boolean goodStu) {
super();
this.name = name;
this.age = age;
GoodStu = goodStu;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args)
{
Student stu1 = new Student("zhangsan",28,false);
Student stu2 = new Student("lis",26,false);
Student stu3 = new Student("wangwu",27,false);
List<Student> stus = new ArrayList<Student>();
stus.add(stu1);
stus.add(stu2);
stus.add(stu3);
print(stus);
System.out.println();
//进行排序
Collections.sort(stus);
print(stus);
System.out.println();
Student stuOfOldAge = stus.get(stus.size()-1);
stuOfOldAge.setGoodStu(true);
System.out.print("Old Student——" + stuOfOldAge.getName() + ":" + stuOfOldAge.getAge() + ":" + stuOfOldAge.isGoodStu());
}
//重写equals
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
{
return false;
}
Student stu = (Student)obj;
return ((stu.name).equals(name)) && ((stu.age) == age) && (stu.GoodStu == GoodStu);
}
//重写hashCode
public int hashCode()
{
int result = 29;
result = 31 * result + name.hashCode();
result = 31 * result + age;
result = 31 * result + (GoodStu? 0:1);
return result;
}
@Override
public int compareTo(Student stu)
{
int cap = age - stu.age;
if(cap != 0)
{
return cap;
}
else
{
return name.compareTo(stu.name);
}
}
//打印方法
private static void print(List<Student> list)
{
for(Student stu:list)
{
System.out.print(stu.getName() + ":" + stu.getAge() + ":" + stu.isGoodStu() + "\t");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGoodStu() {
return GoodStu;
}
public void setGoodStu(boolean goodStu) {
GoodStu = goodStu;
}
}
------解决方案--------------------