设计以下程序

1、定义一个学生类Student,包含三个属性姓名、年龄、性别,创建三个学生对象存入ArrayList集合中。
A:遍历集合遍历输出。
B:求出年龄最大的学生,让后将该对象的姓名变为:张棒棒。
代码如下

学生类

package com.softeem.lesson10.example;

public class Student {

	private String name;
	private String sex;
	private int age;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	public Student(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.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 (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		return true;
	}

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

测试类

package com.softeem.lesson10.example;

import java.util.ArrayList;
import java.util.Arrays;

public class TestStudent {

	public static void main(String[] args) {
		
		Student s1 = new Student("李白", "男", 18);
		Student s2 = new Student("小乔", "女", 28);
		Student s3 = new Student("金克斯", "女", 20);

		ArrayList<Student> list = new ArrayList<>(); //jdk1.7新特性
		list.add(s1);
		list.add(s2);
		list.add(s3);
		list.add(new Student("孙尚香","女",16));
		list.add(new Student("大乔", "女", 88));
		
		//声明临时数组存储所有学生的年龄
		int[] arr = new int[list.size()];
		for(int i = 0;i<list.size();i++) {
			//取出每个学生的年龄装入数组
			arr[i] = list.get(i).getAge();
			System.out.println(list.get(i));
		}
		
		//对数组排序
		Arrays.sort(arr);
		//获取最后一个元素
		int maxAge = arr[arr.length-1];
		
		Student temp = null;
		for(Student s:list) {
			if(s.getAge() == maxAge) {
				s.setName("张棒棒");
				temp = s;
				System.out.println("最大年龄的学生是:"+s);
			}
		}
		
		list.remove(temp);
		
		for (Student s : list) {
			System.out.println(s);
		}
		
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值