01:import java.util.ArrayList;
02:import java.util.Collections;
03:
04:public class BinarySearchDemo1 {
05:
06: static ArrayList cabinet = new ArrayList();
07:
08: public static void main(String args[]) {
09:
10: Unit[] units = {
11: new Unit( "Cabinet Secretariat","内閣官房", "ないかくかんぼう"),
12: new Unit( "Cabinet Office","内閣府", "ないかくふ"),
13: new Unit( "National Public Safety Commission","国家公安委員会", "こっかこうあんいいんかい"),
14: new Unit( "Defense Agency","防衛庁", "ぼうえいちょう"),
15: new Unit( "Financial Services Agency","金融庁", "きんゆうちょう"),
16: new Unit( "Ministry of Public Management, " +
17: "Home Affairs, Posts and Telecommunications","総務省", "そうむしょう"),
18: new Unit( "Ministry of Justice","法務省", "ほうむしょう"),
19: new Unit( "Ministry of Foreign Affairs","外務省", "がいむしょう"),
20: new Unit( "Ministry of Finance","財務省", "ざいむしょう"),
21: new Unit( "Ministry of Education, Culture, Sports, " +
22: "Science and Technology","文部科学省", "もんぶかがくしょう"),
23: new Unit( "Ministry of Health, Labor and Welfare","厚生労働省", "こうせいろうどうしょう"),
24: new Unit( "Ministry of Economy, Trade and Industry","経済産業省", "けいざいさんぎょうしょう"),
25: new Unit( "Ministry of Land, Infrastructure and Transport","国土交通省", "こくどこうつうしょう"),
26: new Unit( "Ministry of Agriculture, Forestry and Fisheries","農林水産省", "のうりんすいさんしょう"),
27: new Unit( "Ministry of Environment","環境省", "かんきょうしょう") };
28:
29: for(int i=0; i<units.length; i++) cabinet.add(units[i]);
30: Collections.sort(cabinet);
31:
32: System.out.println(cabinet);
33: System.out.println("要素数:" + cabinet.size());
34: System.out.println("");
35:
36: Unit key = new Unit( "", "", "きんゆうちょう" );
37: int x = Collections.binarySearch(cabinet, key);
38: printResult(x);
39:
40: key = new Unit( "", "", "こくぼうしょう" );
41: x = Collections.binarySearch(cabinet, key);
42: printResult(x);
43:
44: key = new Unit( "", "", "あ" );
45: x = Collections.binarySearch(cabinet, key);
46: printResult(x);
47:
48: key = new Unit( "", "", "ん" );
49: x = Collections.binarySearch(cabinet, key);
50: printResult(x);
51: }
52:
53: static void printResult(int x) {
54: if(x>=0) { System.out.println("あり: " + cabinet.get(x)); }
55: else { System.out.print("なし: " + (-x-1));
56: if((-x-1)==cabinet.size())
57: System.out.println(" 最後に挿入");
58: else System.out.println(" " + cabinet.get(-x-1) + " の直前に挿入");
59: }
60: }
61:}
62:
63:class Unit implements Comparable {
64: String englishName;
65: String name;
66: String yomi;
67:
68: public Unit( String englishName, String name, String yomi) {
69: this.englishName = englishName;
70: this.name = name;
71: this.yomi = yomi;
72: }
73:
74: public String toString() {
75: return "[" + englishName + " " + name + "]" ;
76: }
77:
78: public int compareTo(Object other) {
79: Unit otherUnit = (Unit)other;
80: return yomi.compareTo( otherUnit.yomi );
81: }
82:}