国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

小議局部類

2019-11-17 05:58:29
字體:
供稿:網(wǎng)友

假如你有一個 Integer 對象的列表,并且你想使用 Coolections.sort 來對它們進行排序。另外,你還要自己指定一個比較器,因為你想按降序而不是升序排列它們。這里有一些代碼示例說明了該怎么做:

import java.util.*;

public class LocalDemo1 {

// 使用實現(xiàn)了 Comparator 的匿名類排序。

static void sortanon(List list) {

Collections.sort(list, new Comparator() {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);

return (cc < 0 ? 1 : cc > 0 ? -1 : 0);

}

});

}

// 使用實現(xiàn)了 Comparator 的局部類排序

static void sortlocal(List list) {

class MyComparator implements Comparator {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);

return (cc < 0 ? 1 : cc > 0 ? -1 : 0);

}

};

Collections.sort(list, new MyComparator());

}

public static void main(String[] args) {

List list1 = new ArrayList();

list1.add(new Integer(1));

list1.add(new Integer(2));

list1.add(new Integer(3));

sortanon(list1);

System.out.PRintln(list1);

List list2 = new ArrayList();

list2.add(new Integer(1));

list2.add(new Integer(2));

list2.add(new Integer(3));

sortlocal(list2);

System.out.println(list2);

}

}

這段程序的輸出如下:

[3, 2, 1]

[3, 2, 1]

上列中使用兩種不同的方法實現(xiàn)了 Comparator 接口。第一種方法使用匿名類,第二種方法使用局部類,二者有何區(qū)別:

一點區(qū)別是格式上的——匿名類的定義比較簡捷,它實際上是下面這個表達式的一部分:

Comparator c = new Comparator() {...};

與之相反,局部類的定義看起來非常類似于常規(guī)的類定義,略為煩瑣。例如,定義局部類內(nèi)時可能用到 “implements”語句,而在匿名類中不需要顯示的使用這條語句。

哪一種格式“更好”取決于你自己的觀點。匿名類的定義會比較難讀,但在不需要使用局部類的地方使用局部類會造成一些錯覺,讓人覺得需要做的事比實際要做的事更多。

讓我們來看看另一個例子,更深層的比較匿名類和局部類:

import java.util.*;

public class LocalDemo2 {

// 使用兩個單獨的匿名類實例對兩個列表進行排序

static void sort1(List list1, List list2) {

Collections.sort(list1, new Comparator() {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);

return (cc < 0 ? 1 : cc > 0 ? -1 : 0);

}

});

Collections.sort(list2, new Comparator() {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);
return (cc < 0 ? 1 : cc > 0 ? -1 : 0);

}

});

}

// 使用一個局部類的兩個實例來對兩個列表進行排序

static void sort2(List list1, List list2) {

class MyComparator implements Comparator {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);

return (cc < 0 ? 1 : cc > 0 ? -1 : 0);

}

}

Collections.sort(list1, new MyComparator());

Collections.sort(list2, new MyComparator());

}

// 使用一個匿名類的一個實例來對兩個列表進行排序

static void sort3(List list1, List list2) {

Comparator cmp = new Comparator() {

public int compare(

Object o1, Object o2) {

int cc = ((Integer)o1).compareTo(o2);


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 绩溪县| 达孜县| 遂溪县| 漳州市| 外汇| 航空| 酉阳| 七台河市| 津南区| 青铜峡市| 新源县| 临猗县| 崇信县| 永年县| 南充市| 牙克石市| 阳朔县| 钟山县| 沁阳市| 海原县| 奉新县| 苍溪县| 芒康县| 西藏| 九江市| 房山区| 萨迦县| 寿光市| 宾川县| 东乌| 清镇市| 眉山市| 奉新县| 武隆县| 都昌县| 宾阳县| 湄潭县| 上犹县| 象州县| 保德县| 于田县|