1004 成绩排名c++java_Interface Comparable_list接口常用方法

在这里插入图片描述
在这里插入图片描述

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList <Student> list = new ArrayList<>();
        for(int i=0; i<n; i++) {
            String name = sc.next();
            String num = sc.next();
            int grade = sc.nextInt();
            Student s = new Student(name, num, grade);
            list.add(s);
            Collections.sort(list);
        }
        System.out.println(list.get(0).name + " " + list.get(0).num);
        System.out.println(list.get(n-1).name + " " + list.get(n-1).num);
    }
}
class Student implements Comparable<Student>{
    String name;
    String num;
    int score;

    public Student(String name, String num, Integer score) {
        this.name = name;
        this.num = num;
        this.score = score;
    }
    public int compareTo(Student s){
        return s.score - score;
    }
}
#include<iostream>
#include<string>
using namespace std;

struct student
{
	string name, number;
	int score;
};

int main()
{
	student s[10000];
	int n,max=-1,min=101,max_position,min_position;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> s[i].name >> s[i].number >> s[i].score;
		if (s[i].score > max)
		{
			max = s[i].score;
			max_position = i;
		}
		if (s[i].score < min)
		{
			min = s[i].score;
			min_position = i;
		}
	}
	cout << s[max_position].name << " " << s[max_position].number<<endl;
	cout << s[min_position].name << " " << s[min_position].number << endl;
	return 0;
}

Interface Comparable

  • 参数类型 :T - 可以将此对象与之进行比较的对象类型

  • 该接口对实现它的每个类的对象强加一个整体排序。 这个排序被称为类的自然排序 ,类的compareTo方法被称为其自然比较方法 。

int compareTo(T o)

  • 将此对象与指定的对象进行比较以进行排序。 返回一个负整数,零或正整数,因为该对象小于,等于或大于指定对象。

List接口常用方法:

1、add(Object element): 向列表的尾部添加指定的元素。
2、size(): 返回列表中的元素个数。
3、get(int index): 返回列表中指定位置的元素,index从0开始。
4、add(int index, Object element): 在列表的指定位置插入指定元素。
5、set(int i, Object element): 将索引i位置元素替换为元素element并返回被替换的元素。
6、clear(): 从列表中移除所有元素。
7、isEmpty(): 判断列表是否包含元素,不包含元素则返回 true,否则返回false。
8、contains(Object o): 如果列表包含指定的元素,则返回 true。
9、remove(int index): 移除列表中指定位置的元素,并返回被删元素。
10、remove(Object o): 移除集合中第一次出现的指定元素,移除成功返回true,否则返回false。
11、iterator(): 返回按适当顺序在列表的元素上进行迭代的迭代器。
ArrayList一样可以使用List的所有方法,所以以ArrayList来演示:

方法使用链接

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DDouble-

你的鼓励是我最大的动力~

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

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

打赏作者

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

抵扣说明:

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

余额充值