我的方法,很挫,用的是Comparator,Comparable类实现的。。。。。。- package com.itheima;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Map;
- import java.util.TreeSet;
- public class TestArray {
-
- public static void main(String[] args) {
- String[][] arr = new String[][] { { "刘海芳", "86" }, { "刘海芳1", "87" },
- { "刘海芳2", "82" } ,{ "刘海芳3", "68" }, { "刘海芳4", "75" },
- { "刘海芳5", "98" }};
- int[] temp=new int[arr.length];
- TreeSet set=new TreeSet();
- for (int i = 0; i < arr.length; i++) {
- Student stu=new Student(arr[i][0],Integer.parseInt(arr[i][1]));
- set.add(stu);
- }
- for (Object object : set) {
- Student stu=(Student)object;
- System.out.println("姓名:"+stu.getName()+" 得分"+stu.getScore());
- }
- }
-
-
- }
- class Student implements Comparator,Comparable{
- //定义属性
- private String name;
- private int score;
- Student(String name,int score){
- this.name=name;
- this.score=score;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public float getScore() {
- return score;
- }
- public void setScore(int score) {
- this.score = score;
- }
- //重新tosring方法,便于打印的直观性
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return this.name;
- }
- //重新compareTo和compare方法
- @Override
- public int compareTo(Object o) {
- Student stu=(Student)o;
- if (this.score > stu.score) {
- return 1;
- } else if (this.score <stu.score) {
- return -1;
- } else {
- return 0;
- }
- }
- @Override
- public int compare(Object o1, Object o2) {
- Student st1 =(Student)o1;
- Student st2 =(Student)o2;
- return st1.name.compareTo(st2.name);
- }
-
- }
-
复制代码 |