您好,登錄后才能下訂單哦!
小編這次要給大家分享的是JAVA基于Arrays.sort()如何實(shí)現(xiàn)數(shù)組升序和降序,文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
java中對(duì)數(shù)組進(jìn)行排序
使用Array.sort() 這個(gè)默認(rèn)是升序
@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());
需要注意的是 不能使用基本類(lèi)型(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數(shù)組,怎么辦,需要先轉(zhuǎn)換一下
@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); } }
看完這篇關(guān)于JAVA基于Arrays.sort()如何實(shí)現(xiàn)數(shù)組升序和降序的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話(huà),可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。