java代码练习 work215

该博客展示了一个Java程序,用于对包含学生对象的数组进行排序。程序中定义了`Student`类,包含了姓名和年龄属性,并实现了`equals`方法。通过`Arrays.sort()`方法和自定义的`StudentComparator`类,根据年龄对学生对象进行升序排序。最后,程序遍历并打印排序后的学生数组。
摘要由CSDN通过智能技术生成

work215.java

package test11;

import java.util.Arrays;
import java.util.Comparator;

public class work215
{

	public static void main(String[] args)
	{
		Student stu[] = new Student[3];
		stu[0] = new Student("果果", 14);
		stu[1] = new Student("飞飞", 15);
		stu[2] = new Student("糖糖", 13);
		Arrays.sort(stu,new StudentComparator());
		
		for (int i = 0; i < stu.length; i++)
		{
			System.out.println(stu[i]);
		}

	}

}
//类的内部没有实现Comparable接口,可以使用一下方式实现比较
class Student
{
	private String name;
	private int age;
	
	public Student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	
	public void setName(String name)
	{
		this.name = name;
	}
	
	public void setAge(int age)
	{
		this.age = age;
	}
	
	public String getName()
	{
		return this.name;
	}
	
	public int getAge()
	{
		return this.age;
	}
	
	@Override
	public String toString()
	{
		return this.name + "\t" + this.age;
	}
	
	public boolean equals(Object obj)
	{
		if(this == obj)
		{
			return true;
		}
		if (!(obj instanceof Student))
		{
			return false;
		}
		
		Student stu = (Student)obj;
		if (stu.name.equals(this.name) && stu.age == this.age)
		{
			return true;
		}
		else 
		{
			return false;
		}
		
	}
	
	
}

class StudentComparator implements Comparator<Student>
{

	@Override
	public int compare(Student o1, Student o2)
	{
		if (o1.equals(o2))
		{
			return 0; //相等
		}
		else if (o1.getAge() < o2.getAge())
		{
			return -1; //小于
		}
		else 
		{
			return 1; //大于
		}
	}
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值