JAVA基于Arrays.sort()实现数组升序和降序
作者:KoMiles 时间:2022-03-11 13:09:48
java中对数组进行排序
使用Array.sort() 这个默认是升序
@Test
public void index4(){
int scores[] = new int[]{1,2,3,89,4};
Arrays.sort(scores);
for (int i:scores
) {
System.out.println(i);
}
}
如果想降序怎么办呢?
使用:Arrays.sort(scores,Collections.reverseOrder());
需要注意的是 不能使用基本类型(int,double, char),如果是int型需要改成Integer,float要改成Float
例子:
@Test
public void index5(){
Integer scores[] = {1,2,3,89,4};
Arrays.sort(scores,Collections.reverseOrder());
for (Integer i:scores
) {
System.out.println(i);
}
}
如果得到的是int数组,怎么办,需要先转换一下
@Test
public void index6(){
int scores[] = new int[]{1,2,3,89,4};
Integer newScores[] = new Integer [5];
for(int i=0;i<scores.length;i++){
newScores[i]= new Integer(scores[i]);
}
Arrays.sort(newScores,Collections.reverseOrder());
for (Integer i:newScores
) {
System.out.println(i);
}
}
来源:https://www.cnblogs.com/wangkongming/p/13061577.html
标签:JAVA,Arrays,sort,数组,升序,降序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java经典算法汇总之选择排序(SelectionSort)
2021-12-23 03:59:52
![](https://img.aspxhome.com/file/2023/3/60343_0s.png)
Java设计模式七大原则之里氏替换原则详解
2022-05-22 13:41:10
![](https://img.aspxhome.com/file/2023/8/61868_0s.jpg)
Maven如何修改打包文件名称
2022-09-02 21:29:52
![](https://img.aspxhome.com/file/2023/5/67685_0s.png)
被kafka-client和springkafka版本坑到自闭及解决
2023-08-23 15:07:36
![](https://img.aspxhome.com/file/2023/2/58452_0s.png)
SpringBoot利用jackson格式化时间的三种方法
2022-03-26 22:28:56
![](https://img.aspxhome.com/file/2023/1/71191_0s.png)
Java实现红黑树(平衡二叉树)的详细过程
2021-08-08 15:03:12
![](https://img.aspxhome.com/file/2023/3/64493_0s.png)
深入浅析C# 11 对 ref 和 struct 的改进
2021-09-27 20:31:47
Java线程之守护线程(Daemon)用法实例
2023-11-29 09:15:13
5分钟搭建SpringCloud Eureka服务注册中心的实现
2022-07-12 05:12:42
![](https://img.aspxhome.com/file/2023/0/79850_0s.png)
js 交互在Flutter 中使用 webview_flutter
2023-07-20 22:40:14
![](https://img.aspxhome.com/file/2023/5/91785_0s.jpg)
关于Java反编译字节码文件
2021-10-07 01:41:32
IDEA不编译除了.java之外的文件的解决办法(推荐)
2023-09-16 15:50:44
![](https://img.aspxhome.com/file/2023/0/58570_0s.png)
Java cookie和session会话技术介绍
2021-12-30 06:51:22
分享java中设置代理的两种方式
2023-10-28 10:48:52
![](https://img.aspxhome.com/file/2023/0/67640_0s.png)
一文探索Java文件读写更高效方式
2021-12-20 08:31:22
Java实现两人五子棋游戏(五) 判断是否有一方胜出
2022-03-03 18:29:44
![](https://img.aspxhome.com/file/2023/5/64955_0s.jpg)
C#判断获取的是文件夹还是文件的实例
2022-11-25 05:00:01
详解java.lang.reflect.Modifier.isInterface()方法
2023-07-27 18:25:25
springboot之端口设置和contextpath的配置方式
2023-10-05 14:16:20
简单聊一聊Java线程池ThreadPoolExecutor
2021-10-23 15:56:58
![](https://img.aspxhome.com/file/2023/3/64053_0s.jpg)