自定义排序函数
1.定义要排序的类
2.写个类继承排序接口,重写排序函数
3.在主类里调用排序函数
String自带compareTo是按字符顺序比较
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String sn = sc.nextLine();
String str1 = sc.nextLine();
String str2 = sc.nextLine();
int n = Integer.valueOf(sn);
String[] sh = new String[n];
int[] h = new int[n];
String[] s = new String[n];
sh = str1.split(" ");
s = str2.split(" ");
for(int i=0; i<n; i++) h[i] = Integer.valueOf(sh[i]);
List<User> users = new ArrayList<>();
for(int i=0; i<n; i++) {
User u = new User(h[i],s[i]);
users.add(u);
}
Collections.sort(users,new UserComparator());
int k=0;
for (User user : users) {
if(k==n-1) System.out.print(user.getName());
else System.out.print(user.getName() + " ");
k++;
}
}
}
class User{
int high;
String name;
public User(int high, String name) {
this.high = high;
this.name = name;
}
public void setHigh(int high) {
this.high = high;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getHigh() {
return high;
}
/*int compareTo(User use){
return high - use.getHigh();
}*/
}
class UserComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
User user1 = (User) o1;
User user2 = (User) o2;
if (user1.getHigh() > user2.getHigh()) {
return 1;
} else if (user1.getHigh() < user2.getHigh()) {
return -1;
} else {
return user1.getName().compareTo(user2.getName());
}
}
}

该博客展示了如何在Java中实现自定义排序。通过创建一个`User`类,存储高度和名字,然后定义一个`UserComparator`类来重写`Comparator`接口,实现了根据高度和名字的字母顺序进行排序。在主程序中,读取输入,创建`User`对象列表,并使用`Collections.sort()`方法进行排序,最后输出排序后的用户名字。
889

被折叠的 条评论
为什么被折叠?



