java 51_学习java第51天

1.Comparable 接口的定义:

public interface Comparable{

public int compareTo(T o)

}

接口中只有一个 compareTo 方法,该方法返回一个 int 类型的数据,但是 int 的值只能是3种:

*1:表示大于

*-1:表示小于

*0:表示相等

//设计一个学生类,包含姓名、年龄、成绩,并产生一个对象数组,要求按成绩由高到底排序,如果成绩相等,则按年龄由低到高排序

import java.util.Arrays;

class Student implements Comparable{

private String name;

private int age;

private float score;

public Student(String name,int age,float score){

this.name = name;

this.age = age;

this.score = score;

}

public String toString(){

return name + "\t\t" + age + "\t\t" + score;

}

public int compareTo(Student stu){

if (this.score>stu.score){

return -1;

}else if(this.score < stu.score){

return 1;

}else {

if (this.age > stu.age){

return 1;

}else if (this.age

return -1;

}else {

return 0;

}

}

}

}

public class Root{

public static void main(String[] args) {

Student[] stu = {new Student("stu1",20,90.0f),

new Student("stu2",22,90.0f),

new Student("stu3",20,70.0f),

new Student("stu4",34,98)};

Arrays.sort(stu);

for (Student x:stu){

System.out.println(x);

}

}

}

实现Comparable接口的类,不能排序

//对Person类进行排序

import.java.util.HashSet;

import.java.util.Set;

piblic class ComparaDemo {

public static void main(String[] args) {

Set set = new HashSet();

set.add(new Person("张三",20));

set.add(new Person("李四",21));

set.add(new Person("王五",22));

System.out.println(set);

}

}

2.明天学习内容:增强for循环

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值