日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

java數組排序Arrays.sort,以及結合Comparator

系統 1974 0
Sorting an Array

1. 數字排序? int[] intArray = new int[] { 4, 1, 3, -23 };
Arrays.sort(intArray);
輸出: [-23, 1, 3, 4]
2. 字符串排序,先大寫后小寫 String[] strArray = new String[]{ "z", "a", "C" };
Arrays.sort(strArray);
輸出: [C, a, z]
3. 嚴格按字母表順序排序,也就是忽略大小寫排序 Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
輸出: [a, C, z]
4. 反向排序, Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
輸出:[z, a, C]
5. 忽略大小寫反向排序 Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
輸出: [z, C, a]

對于整數、字符串排序,jdk提供了默認的實現,如果要對一個對象數組排序,則要自己實現java.util.Comparator接口。

示例:

    import java.util.Arrays;
import java.util.Comparator;

class Cat {
	private String name;
	private float weight;
	
	public Cat(String name, float weight) {
		setName(name);
		setWeight(weight);
	}
	
	public Cat() {
	
	}
	
	public String getName() {
		return name;
	}
	
	public float getWeight() {
		return weight;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setWeight(float weight) {
		this.weight = weight;
	}
}

//創建一個比較器
class ByWeightComparator implements Comparator {
	public final int compare(Object c1, Object c2) {
		if(((Cat)c1).getWeight() > ((Cat)c2).getWeight()) {
			return 1;
		} else if(((Cat)c1).getWeight() == ((Cat)c2).getWeight()) {
					return 0;
		} else return -1;
	}
}

public class CatArrSortTest {
	public static void main(String[] args) {
		Cat c1 = new Cat("w", 100);
		Cat c2 = new Cat("d", 50);
		Cat c3 = new Cat("a", 80);
		Cat[] c = new Cat[]{c1, c2, c3};
		
		System.out.println("排序前:");
		for( Cat c4 : c) {
			System.out.print(c4.getName() + "," + c4.getWeight() + "\t");
		}

		Arrays.sort(c, new ByWeightComparator());

		System.out.println("\n排序后:");
		for( Cat c4 : c) {
			System.out.print(c4.getName() + "," + c4.getWeight() + "\t");
		}
	}
}

  


運行結果:

java數組排序Arrays.sort,以及結合Comparator接口的用法


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 博客| 淮北市| 定远县| 黑龙江省| 楚雄市| 白城市| 临朐县| 绥芬河市| 泰宁县| 泰顺县| 博客| 香河县| 德庆县| 镇原县| 伊春市| 思南县| 焉耆| 稻城县| 元江| 凭祥市| 南郑县| 阿拉善盟| 彰化县| 内丘县| 满城县| 米脂县| 钟山县| 丹江口市| 渭源县| 商丘市| 永安市| 巴林右旗| 扎兰屯市| 子长县| 安化县| 观塘区| 德庆县| 台安县| 红河县| 赣榆县| 芒康县|