2009年6月16日火曜日

カンマ区切りの文字列を扱う

カンマ区切りの文字列で
2つ目に区切られた語を取り出したい場合、
下記の2つでどの方法が早いか実験。
public static void main(String[] args) {
     long start, goal;
     String str = "漢字,ひらがな,カタカナ,ローマ字";
     start = System.currentTimeMillis();
     for (int i=0; i < 100000; i++){ func1(str);}
     goal = System.currentTimeMillis();
     System.out.println("func1: " + (goal - start));

     start = System.currentTimeMillis();
     for (int i=0; i < 100000; i++){ func2(str);}
     goal = System.currentTimeMillis();
     System.out.println("func1: " + (goal - start));

     }
     static String func1(String str) {
         int index = str.indexOf(",") + 1;
         return str.substring(index, str.indexOf(",", index));
     }
     static String func2(String str) {
         return str.split(",")[1];
     }
結果は
func1: 16
func1: 438

1行で書けても遅い。ケースバイケースで使い分け。

2009年6月15日月曜日

InetAddress

InetAddress のインスタンスを ip アドレスから作成。
バイトの範囲を超える場合はキャストする。

InetAddress add = InetAddress.getByAddress(
new byte[]{(byte)203, (byte)216, (byte)235, (byte)154});
System.out.println(add.getHostName());

もしくは
InetAddress add = InetAddress.getByName("203.216.235.154");

2009年6月13日土曜日

HashMap を Value 値でソート

HashMap を Value 値でソートしてみた。 (JDK6)

HashMap の作成
Map scores = new HashMap();

Key は String、 Value は数値から Integer オブジェクトを入れてある。

昇順でソートしてみると

List<Map.Entry> entries = new ArrayList<Map.Entry>(scores.entrySet());
Collections.sort(entries, new Comparator(){
    public int compare(Object o1, Object o2){
        Map.Entry e1 =(Map.Entry)o1;
        Map.Entry e2 =(Map.Entry)o2;
        return ((Integer)e1.getValue()).compareTo((Integer)e2.getValue());
    }
});

取り出しは

for (Map.Entry entry : entries) {
    // entry.getKey()entry.getValue() を使ってみた。
}