/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowledgement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgement may appear in the software itself,
 *    if and wherever such third-party acknowledgements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.commons.lang.time;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 * <p>FastDateFormat は高速に動作するスレッドセーフな {@link java.text.SimpleDateFormat} です。
 * {@primary FastDateFormat is a fast and thread-safe version of
 * {@link java.text.SimpleDateFormat}.}</p>
 * 
 * <p>このクラスは <code>SimpleDateFormat</code>
 * を使用したフォーマットを行う大抵の処理をそのまま置き換えることが出来ます。
 * このクラスは特にマルチスレッドで動作するサーバ環境で有用です。
 * <code>SimpleDateFormat</code> は全ての JDK のバージョンにおいてスレッドセーフではなく、
 * Sun はこれをバグまたは要望として対応することもありません。
 * {@primary This class can be used as a direct replacement to
 * <code>SimpleDateFormat</code> in most formatting situations.
 * This class is especially useful in multi-threaded server environments.
 * <code>SimpleDateFormat</code> is not thread-safe in any JDK version,
 * nor will it be as Sun have closed the bug/RFE.}
 * </p>
 *
 * <p>このクラスはフォーマットの処理にのみ対応しますが、全てのパターンのフォーマットの処理が
 * SimpleDateFormat と互換性を持ちます(タイムゾーンを除いて - 以下を参照)。
 * {@primary Only formatting is supported, but all patterns are compatible with
 * SimpleDateFormat (except time zones - see below).}</p>
 *
 * <p>Java 1.4 は RFC822 のフォーマットでタイムゾーンを表す <code>'Z'</code>
 * という新しいパターンの文字を取り入れました(例えば <code>+0800</code> や <code>-1100</code>)。
 * このクラスでは(全ての JDK のバージョンで)この文字を使用することができます。
 * {@primary Java 1.4 introduced a new pattern letter, <code>'Z'</code>, to represent
 * time zones in RFC822 format (eg. <code>+0800</code> or <code>-1100</code>).
 * This pattern letter can be used here (on all JDK versions).}</p>
 *
 * <p>加えて、 <code>'ZZ'</code> のパターンは ISO8601
 * のフルフォーマットのタイムゾーンを表します(例えば <code>+08:00</code> や <code>-11:00</code>)。
 * これは Java 1.4 との多少の非互換性を招きますが、有用な機能を得ることとなります。
 * {@primary In addition, the pattern <code>'ZZ'</code> has been made to represent
 * ISO8601 full format time zones (eg. <code>+08:00</code> or <code>-11:00</code>).
 * This introduces a minor incompatability with Java 1.4, but at a gain of
 * useful functionality.}</p>
 *
 * @author TeaTrove project
 * @author Brian S O'Neill
 * @author Sean Schofield
 * @author Gary Gregory
 * @author Stephen Colebourne
 * @translator 日置 聡
 * @status firstdraft
 * @update 2003/09/22
 * @memo 2.0新規
 * @since 2.0
 * @version $Id: FastDateFormat.java,v 1.1.1.1 2004/02/13 10:02:05 hioki Exp $
 */
public class FastDateFormat extends Format {
    // A lot of the speed in this class comes from caching, but some comes
    // from the special int to StringBuffer conversion.
    //
    // The following produces a padded 2 digit number:
    //   buffer.append((char)(value / 10 + '0'));
    //   buffer.append((char)(value % 10 + '0'));
    //
    // Note that the fastest append to StringBuffer is a single char (used here).
    // Note that Integer.toString() is not called, the conversion is simply
    // taking the value and adding (mathematically) the ASCII value for '0'.
    // So, don't change this code! It works and is very fast.
    
    /**
     * FULL ロケールに依存した日付または時間のフォーマットのための定数です。
     * {@primary FULL locale dependent date or time style.}
     */
    public static final int FULL = DateFormat.FULL;
    /**
     * LONG ロケールに依存した日付または時間のフォーマットのための定数です。
     * {@primary LONG locale dependent date or time style.}
     */
    public static final int LONG = DateFormat.LONG;
    /**
     * MEDIUM ロケールに依存した日付または時間のフォーマットのための定数です。
     * {@primary MEDIUM locale dependent date or time style.}
     */
    public static final int MEDIUM = DateFormat.MEDIUM;
    /**
     * SHORT ロケールに依存した日付または時間のフォーマットのための定数です。
     * {@primary SHORT locale dependent date or time style.}
     */
    public static final int SHORT = DateFormat.SHORT;
    
    // package scoped as used by inner class
    static final double LOG_10 = Math.log(10);

    private static String cDefaultPattern;

    private static Map cInstanceCache = new HashMap(7);
    private static Map cDateInstanceCache = new HashMap(7);
    private static Map cTimeInstanceCache = new HashMap(7);
    private static Map cDateTimeInstanceCache = new HashMap(7);
    private static Map cTimeZoneDisplayCache = new HashMap(7);

    /**
     * パターンです。{@primary The pattern.}
     */
    private final String mPattern;
    /**
     * タイムゾーンです。{@primary The time zone.}
     */
    private final TimeZone mTimeZone;
    /**
     * Calendar のタイムゾーンを上書きするかどうか。
     * {@primary  Whether the time zone overrides any on Calendars.}
     */
    private final boolean mTimeZoneForced;
    /**
     * ロケールです。{@primary The locale.}
     */
    private final Locale mLocale;
    /**
     * デフォルトのロケールを上書きするかどうか。
     * {@primary Whether the locale overrides the default.}
     */
    private final boolean mLocaleForced;
    /**
     * パースされたルールです。{@primary The parsed rules.}
     */
    private Rule[] mRules;
    /**
     * 予測される最大長です。
     * {@primary The estimated maximum length.}
     */
    private int mMaxLengthEstimate;

    //-----------------------------------------------------------------------
    /**
     * <p>デフォルトのロケールとデフォルトのパターンを用いてフォーマッターのインスタンスを取得します。
     * {@primary Gets a formatter instance using the default pattern in the
     * default locale.}</p>
     * 
     * @return 日付/時間のフォーマッター
     * {@primary a date/time formatter}
     */
    public static FastDateFormat getInstance() {
        return getInstance(getDefaultPattern(), null, null);
    }

    /**
     * <p>デフォルトのロケールと指定されたパターンを用いてフォーマッターのインスタンスを取得します。
     * {@primary Gets a formatter instance using the specified pattern in the
     * default locale.}</p>
     * 
     * @param pattern  {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary {@link java.text.SimpleDateFormat} compatible pattern}
     * @return パターンをベースにした日付/時間のフォーマッター
     * {@primary a pattern based date/time formatter}
     * @throws IllegalArgumentException パターンが不正な場合
     * {@primary if pattern is invalid}
     */
    public static FastDateFormat getInstance(String pattern) {
        return getInstance(pattern, null, null);
    }

    /**
     * <p>指定されたパターンと指定されたタイムゾーンを用いてフォーマッターのインスタンスを取得します。
     * {@primary Gets a formatter instance using the specified pattern and
     * time zone.}</p>
     * 
     * @param pattern  {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary {@link java.text.SimpleDateFormat} compatible pattern}
     * @param timeZone  フォーマットされた日付のタイムゾーンを上書きする任意のタイムゾーン
     * {@primary optional time zone, overrides time zone of formatted date}
     * @return パターンをベースにした日付/時間のフォーマッター
     * {@primary a pattern based date/time formatter}
     * @throws IllegalArgumentException パターンが不正な場合
     * {@primary if pattern is invalid}
     */
    public static FastDateFormat getInstance(String pattern, TimeZone timeZone) {
        return getInstance(pattern, timeZone, null);
    }

    /**
     * <p>指定されたパターンと指定されたロケールを用いてフォーマッターのインスタンスを取得します。
     * {@primary Gets a formatter instance using the specified pattern and
     * locale.}</p>
     * 
     * @param pattern  {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary {@link java.text.SimpleDateFormat} compatible pattern}
     * @param locale  システムのロケールを上書きする任意のロケール
     * {@primary optional locale, overrides system locale}
     * @return パターンをベースにした日付/時間のフォーマッター
     * {@primary a pattern based date/time formatter}
     * @throws IllegalArgumentException パターンが不正な場合
     * {@primary if pattern is invalid}
     */
    public static FastDateFormat getInstance(String pattern, Locale locale) {
        return getInstance(pattern, null, locale);
    }

    /**
     * <p>指定されたパターン、タイムゾーン、ロケールを用いてフォーマッターのインスタンスを取得します。
     * {@primary Gets a formatter instance using the specified pattern, time zone
     * and locale.}</p>
     * 
     * @param pattern  {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary {@link java.text.SimpleDateFormat} compatible pattern}
     * @param timeZone  フォーマットされた日付のタイムゾーンを上書きする任意のタイムゾーン
     * {@primary optional time zone, overrides time zone of formatted date}
     * @param locale  システムのロケールを上書きする任意のロケール
     * {@primary optional locale, overrides system locale}
     * @return パターンをベースにした日付/時間のフォーマッター
     * {@primary a pattern based date/time formatter}
     * @throws パターンが不正または <code>null</code> な場合
     * {@primary IllegalArgumentException if pattern is invalid or <code>null</code>}
     */
    public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
        FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale);
        FastDateFormat format = (FastDateFormat) cInstanceCache.get(emptyFormat);
        if (format == null) {
            format = emptyFormat;
            format.init();  // convert shell format into usable one
            cInstanceCache.put(format, format);  // this is OK!
        }
        return format;
    }

    /**
     * <p>指定されたスタイル、タイムゾーン、ロケールを用いて日付のフォーマッターインスタンスを取得します。
     * {@primary Gets a date formatter instance using the specified style, time
     * zone and locale.}</p>
     * 
     * @param style  日付のスタイル:FULL または LONG または MEDIUM または SHORT
     * {@primary date style: FULL, LONG, MEDIUM, or SHORT}
     * @param timeZone  フォーマットされた日付のタイムゾーンを上書きする任意のタイムゾーン
     * {@primary optional time zone, overrides time zone of formatted date}
     * @param locale  システムのロケールを上書きする任意のロケール
     * {@primary optional locale, overrides system locale}
     * @return ローカライズされた標準の日付のフォーマッター
     * {@primary a localized standard date formatter}
     * @throws IllegalArgumentException ロケールが定義された日付のパターンを持っていない場合
     * {@primary if the Locale has no date pattern defined}
     */
    public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
        Object key = new Integer(style);
        if (timeZone != null) {
            key = new Pair(key, timeZone);
        }
        if (locale == null) {
            key = new Pair(key, locale);
        }

        FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
        if (format == null) {
            if (locale == null) {
                locale = Locale.getDefault();
            }

            try {
                SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
                String pattern = formatter.toPattern();
                format = getInstance(pattern, timeZone, locale);
                cDateInstanceCache.put(key, format);
                
            } catch (ClassCastException ex) {
                throw new IllegalArgumentException("No date pattern for locale: " + locale);
            }
        }
        return format;
    }

    /**
     * <p>指定されたスタイル、タイムゾーン、ロケールを用いて時間のフォーマッターインスタンスを取得します。
     * {@primary Gets a time formatter instance using the specified style, time
     * zone and locale.}</p>
     * 
     * @param style  時間のスタイル:FULL または LONG または MEDIUM または SHORT
     * {@primary time style: FULL, LONG, MEDIUM, or SHORT}
     * @param timeZone  フォーマットされた日付のタイムゾーンを上書きする任意のタイムゾーン
     * {@primary optional time zone, overrides time zone of formatted date}
     * @param locale  システムのロケールを上書きする任意のロケール
     * {@primary optional locale, overrides system locale}
     * @return ローカライズされた標準の時間のフォーマッター
     * {@primary a localized standard time formatter}
     * @throws IllegalArgumentException ロケールが定義された時間のパターンを持っていない場合
     * {@primary if the Locale has no time pattern defined}
     */
    public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
        Object key = new Integer(style);
        if (timeZone != null) {
            key = new Pair(key, timeZone);
        }
        if (locale != null) {
            key = new Pair(key, locale);
        }

        FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key);
        if (format == null) {
            if (locale == null) {
                locale = Locale.getDefault();
            }

            try {
                SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
                String pattern = formatter.toPattern();
                format = getInstance(pattern, timeZone, locale);
                cTimeInstanceCache.put(key, format);
            
            } catch (ClassCastException ex) {
                throw new IllegalArgumentException("No date pattern for locale: " + locale);
            }
        }
        return format;
    }

    /**
     * <p>指定されたスタイル、タイムゾーン、ロケールを用いて日付/時間のフォーマッターインスタンスを取得します。
     * {@primary Gets a date/time formatter instance using the specified style,
     * time zone and locale.}</p>
     * 
     * @param dateStyle  日付のスタイル:FULL または LONG または MEDIUM または SHORT
     * {@primary date style: FULL, LONG, MEDIUM, or SHORT}
     * @param timeStyle  時間のスタイル:FULL または LONG または MEDIUM または SHORT
     * {@primary time style: FULL, LONG, MEDIUM, or SHORT}
     * @param timeZone  フォーマットされた日付のタイムゾーンを上書きする任意のタイムゾーン
     * {@primary optional time zone, overrides time zone of formatted date}
     * @param locale  システムのロケールを上書きする任意のロケール
     * {@primary optional locale, overrides system locale}
     * @return a localized standard date/time formatter
     * @return ローカライズされた標準の日付/時間のフォーマッター
     * {@primary a localized standard date/time formatter}
     * @throws IllegalArgumentException ロケールが定義された日付/時間のパターンを持っていない場合
     * {@primary if the Locale has no date/time pattern defined}
     */
    public static synchronized FastDateFormat getDateTimeInstance(
            int dateStyle, int timeStyle, TimeZone timeZone, Locale locale) {

        Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
        if (timeZone != null) {
            key = new Pair(key, timeZone);
        }
        if (locale != null) {
            key = new Pair(key, locale);
        }

        FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
        if (format == null) {
            if (locale == null) {
                locale = Locale.getDefault();
            }

            try {
                SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
                String pattern = formatter.toPattern();
                format = getInstance(pattern, timeZone, locale);
                cDateTimeInstanceCache.put(key, format);
                
            } catch (ClassCastException ex) {
                throw new IllegalArgumentException("No date time pattern for locale: " + locale);
            }
        }
        return format;
    }

    //-----------------------------------------------------------------------
    /**
     * <p>タイムゾーンの表示名を(パフォーマンスのために)キャッシュから取得します。
     * {@primary Gets the time zone display name, using a cache for performance.}</p>
     * 
     * @param tz  要求するタイムゾーン
     * {@primary the zone to query}
     * @param daylight  true の場合、夏時間
     * {@primary true if daylight savings}
     * @param style  <code>TimeZone.LONG</code> または <code>TimeZone.SHORT</code> で表現されるスタイル
     * {@primary the style to use <code>TimeZone.LONG</code> or <code>TimeZone.SHORT</code>}
     * @param locale  使用するロケール
     * {@primary the locale to use}
     * @return タイムゾーンの文字表現
     * {@primary the textual name of the time zone}
     */
    static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
        Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
        String value = (String) cTimeZoneDisplayCache.get(key);
        if (value == null) {
            // This is a very slow call, so cache the results.
            value = tz.getDisplayName(daylight, style, locale);
            cTimeZoneDisplayCache.put(key, value);
        }
        return value;
    }

    /**
     * <p>デフォルトのパターンを取得します。{@primary Gets the default pattern.}</p>
     * 
     * @return デフォルトのパターン
     * {@primary the default pattern}
     */
    private static synchronized String getDefaultPattern() {
        if (cDefaultPattern == null) {
            cDefaultPattern = new SimpleDateFormat().toPattern();
        }
        return cDefaultPattern;
    }

    // Constructor
    //-----------------------------------------------------------------------
    /**
     * <p>新たな FastDateFormat を生成します。
     * {@primary Constructs a new FastDateFormat.}</p>
     * 
     * @param pattern  {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary {@link java.text.SimpleDateFormat} compatible pattern}
     * @param timeZone  使用されるタイムゾーン、 <code>null</code> が指定された場合、
     * <code>Date</code> と <code>Calendar</code> に対してデフォルトの値が使用されます
     * {@primary time zone to use, <code>null</code> means use
     *  default for <code>Date</code> and value within for
     *  <code>Calendar</code>}
     * @param locale  使用されるロケール、 <code>null</code> が指定された場合、システムのデフォルトが使用されます
     * {@primary locale, <code>null</code> means use system default}
     * @throws IllegalArgumentException パターンが不正または <code>null</code> の場合
     * {@primary if pattern is invalid or <code>null</code>}
     */
    protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
        super();
        if (pattern == null) {
            throw new IllegalArgumentException("The pattern must not be null");
        }
        mPattern = pattern;
        
        mTimeZoneForced = (timeZone != null);
        if (timeZone == null) {
            timeZone = TimeZone.getDefault();
        }
        mTimeZone = timeZone;
        
        mLocaleForced = (locale != null);
        if (locale == null) {
            locale = Locale.getDefault();
        }
        mLocale = locale;
    }

    /**
     * <p>最初に使用される際のインスタンスの初期化を行います。
     * {@primary Initialise the instance for first use.}</p>
     */
    protected void init() {
        List rulesList = parsePattern();
        mRules = (Rule[]) rulesList.toArray(new Rule[rulesList.size()]);

        int len = 0;
        for (int i=mRules.length; --i >= 0; ) {
            len += mRules[i].estimateLength();
        }

        mMaxLengthEstimate = len;
    }

    // Parse the pattern
    //-----------------------------------------------------------------------
    /**
     * <p>パターンから生成された Rule のリストを返します。
     * {@primary Returns a list of Rules given a pattern.}</p>
     * 
     * @return Rule オブジェクトの <code>List</code>
     * {@primary a <code>List</code> of Rule objects}
     * @throws IllegalArgumentException パターンが不正な場合
     * {@primary if pattern is invalid}
     */
    protected List parsePattern() {
        DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
        List rules = new ArrayList();

        String[] ERAs = symbols.getEras();
        String[] months = symbols.getMonths();
        String[] shortMonths = symbols.getShortMonths();
        String[] weekdays = symbols.getWeekdays();
        String[] shortWeekdays = symbols.getShortWeekdays();
        String[] AmPmStrings = symbols.getAmPmStrings();

        int length = mPattern.length();
        int[] indexRef = new int[1];

        for (int i = 0; i < length; i++) {
            indexRef[0] = i;
            String token = parseToken(mPattern, indexRef);
            i = indexRef[0];

            int tokenLen = token.length();
            if (tokenLen == 0) {
                break;
            }

            Rule rule;
            char c = token.charAt(0);

            switch (c) {
            case 'G': // era designator (text)
                rule = new TextField(Calendar.ERA, ERAs);
                break;
            case 'y': // year (number)
                if (tokenLen >= 4) {
                    rule = UnpaddedNumberField.INSTANCE_YEAR;
                } else {
                    rule = TwoDigitYearField.INSTANCE;
                }
                break;
            case 'M': // month in year (text and number)
                if (tokenLen >= 4) {
                    rule = new TextField(Calendar.MONTH, months);
                } else if (tokenLen == 3) {
                    rule = new TextField(Calendar.MONTH, shortMonths);
                } else if (tokenLen == 2) {
                    rule = TwoDigitMonthField.INSTANCE;
                } else {
                    rule = UnpaddedMonthField.INSTANCE;
                }
                break;
            case 'd': // day in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
                break;
            case 'h': // hour in am/pm (number, 1..12)
                rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
                break;
            case 'H': // hour in day (number, 0..23)
                rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
                break;
            case 'm': // minute in hour (number)
                rule = selectNumberRule(Calendar.MINUTE, tokenLen);
                break;
            case 's': // second in minute (number)
                rule = selectNumberRule(Calendar.SECOND, tokenLen);
                break;
            case 'S': // millisecond (number)
                rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
                break;
            case 'E': // day in week (text)
                rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
                break;
            case 'D': // day in year (number)
                rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
                break;
            case 'F': // day of week in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
                break;
            case 'w': // week in year (number)
                rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
                break;
            case 'W': // week in month (number)
                rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
                break;
            case 'a': // am/pm marker (text)
                rule = new TextField(Calendar.AM_PM, AmPmStrings);
                break;
            case 'k': // hour in day (1..24)
                rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
                break;
            case 'K': // hour in am/pm (0..11)
                rule = selectNumberRule(Calendar.HOUR, tokenLen);
                break;
            case 'z': // time zone (text)
                if (tokenLen >= 4) {
                    rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG);
                } else {
                    rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT);
                }
                break;
            case 'Z': // time zone (value)
                if (tokenLen == 1) {
                    rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
                } else {
                    rule = TimeZoneNumberRule.INSTANCE_COLON;
                }
                break;
            case '\'': // literal text
                String sub = token.substring(1);
                if (sub.length() == 1) {
                    rule = new CharacterLiteral(sub.charAt(0));
                } else {
                    rule = new StringLiteral(sub);
                }
                break;
            default:
                throw new IllegalArgumentException("Illegal pattern component: " + token);
            }

            rules.add(rule);
        }

        return rules;
    }

    /**
     * <p>トークンのパースを行います。
     * {@primary Performs the parsing of tokens.}</p>
     * 
     * @param pattern  パターン
     * {@primary the pattern}
     * @param indexRef  参照のインデックス
     * {@primary index references}
     * @return パースされたトークン
     * {@primary parsed token}
     */
    protected String parseToken(String pattern, int[] indexRef) {
        StringBuffer buf = new StringBuffer();

        int i = indexRef[0];
        int length = pattern.length();

        char c = pattern.charAt(i);
        if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
            // Scan a run of the same character, which indicates a time
            // pattern.
            buf.append(c);

            while (i + 1 < length) {
                char peek = pattern.charAt(i + 1);
                if (peek == c) {
                    buf.append(c);
                    i++;
                } else {
                    break;
                }
            }
        } else {
            // This will identify token as text.
            buf.append('\'');

            boolean inLiteral = false;

            for (; i < length; i++) {
                c = pattern.charAt(i);

                if (c == '\'') {
                    if (i + 1 < length && pattern.charAt(i + 1) == '\'') {
                        // '' is treated as escaped '
                        i++;
                        buf.append(c);
                    } else {
                        inLiteral = !inLiteral;
                    }
                } else if (!inLiteral &&
                         (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
                    i--;
                    break;
                } else {
                    buf.append(c);
                }
            }
        }

        indexRef[0] = i;
        return buf.toString();
    }

    /**
     * <p>要求されたパディングに対する適切なルールを返します。
     * {@primary Gets an appropriate rule for the padding required.}</p>
     * 
     * @param field  ルールを取得する対象となるフィールド
     * {@primary the field to get a rule for}
     * @param padding  要求されたパディング
     * {@primary the padding required}
     * @return パディングに対応する新たなルール
     * {@primary a new rule with the correct padding}
     */
    protected NumberRule selectNumberRule(int field, int padding) {
        switch (padding) {
        case 1:
            return new UnpaddedNumberField(field);
        case 2:
            return new TwoDigitNumberField(field);
        default:
            return new PaddedNumberField(field, padding);
        }
    }

    // Format methods
    //-----------------------------------------------------------------------
    /**
     * <p><code>Date</code> オブジェクトまたは <code>Calendar</code> オブジェクトをフォーマットします。
     * {@primary Format either a <code>Date</code> or a <code>Calendar</code> object.}</p>
     * 
     * @param obj  フォーマットの対象となるオブジェクト
     * {@primary the object to format}
     * @param toAppendTo  書き込み先となるバッファ
     * {@primary the buffer to append to}
     * @param pos  フォーマットする位置 - 無効
     * {@primary the position - ignored}
     * @return フォーマットの結果が出力されたバッファ
     * {@primary the buffer passed in}
     */
    public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
        if (obj instanceof Date) {
            return format((Date) obj, toAppendTo);
        } else if (obj instanceof Calendar) {
            return format((Calendar) obj, toAppendTo);
        } else {
            throw new IllegalArgumentException("Unknown class: " +
                (obj == null ? "<null>" : obj.getClass().getName()));
        }
    }

    /**
     * <p><code>Date</code> オブジェクトをフォーマットします。
     * {@primary Formats a <code>Date</code> object.}</p>
     * 
     * @param date  フォーマットの対象となる日付
     * {@primary the date to format}
     * @return フォーマットされた文字列
     * {@primary the formatted string}
     */
    public String format(Date date) {
        Calendar c = new GregorianCalendar(mTimeZone);
        c.setTime(date);
        return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
    }

    /**
     * <p><code>Calendar</code> オブジェクトをフォーマットします。
     * {@primary Formats a <code>Calendar</code> object.}</p>
     * 
     * @param calendar  フォーマットの対象となるカレンダー
     * {@primary the calendar to format}
     * @return フォーマットされた文字列
     * {@primary the formatted string}
     */
    public String format(Calendar calendar) {
        return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString();
    }

    /**
     * <p><code>Date</code> オブジェクトをフォーマットし、指定された
     * <code>StringBuffer</code> に出力します。
     * {@primary Formats a <code>Date</code> object into the supplied <code>StringBuffer</code>.}</p>
     * 
     * @param date  フォーマットの対象となる日付
     * {@primary the date to format}
     * @param buf  書き込み先となるバッファ
     * {@primary the buffer to append to}
     * @return 指定された文字列のバッファ
     * {@primary the specified string buffer}
     */
    public StringBuffer format(Date date, StringBuffer buf) {
        Calendar c = new GregorianCalendar(mTimeZone);
        c.setTime(date);
        return applyRules(c, buf);
    }

    /**
     * <p><code>Calendar</code> オブジェクトをフォーマットし、指定された
     * <code>StringBuffer</code> に出力します。
     * {@primary Formats a <code>Calendar</code> object into the supplied <code>StringBuffer</code>.}</p>
     * 
     * @param calendar  フォーマットの対象となるカレンダー
     * {@primary the calendar to format}
     * @param buf  書き込み先となるバッファ
     * {@primary the buffer to append to}
     * @return 指定された文字列のバッファ
     * {@primary the specified string buffer}
     */
    public StringBuffer format(Calendar calendar, StringBuffer buf) {
        if (mTimeZoneForced) {
            calendar = (Calendar) calendar.clone();
            calendar.setTimeZone(mTimeZone);
        }
        return applyRules(calendar, buf);
    }

    /**
     * <p>指定されたカレンダーにルールを適用してフォーマットを実施します。
     * {@primary Performs the formatting by applying the rules to the
     * specified calendar.}</p>
     * 
     * @param calendar  フォーマットの対象となるカレンダー
     * {@primary the calendar to format}
     * @param buf  書き込み先となるバッファ
     * {@primary the buffer to append to}
     * @return 指定された文字列のバッファ
     * {@primary the specified string buffer}
     */
    protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) {
        Rule[] rules = mRules;
        int len = mRules.length;
        for (int i = 0; i < len; i++) {
            rules[i].appendTo(buf, calendar);
        }
        return buf;
    }

    // Parsing
    //-----------------------------------------------------------------------
    /**
     * <p>パース処理はサポートされません。{@primary Parsing not supported.}</p>
     * 
     * @param source  パースの対象となる文字列
     * {@primary the string to parse}
     * @param pos  パーすする位置
     * {@primary the parsing position}
     * @return サポートされないため、<code>null</code>
     * {@primary <code>null</code> as not supported}
     */
    public Object parseObject(String source, ParsePosition pos) {
        pos.setIndex(0);
        pos.setErrorIndex(0);
        return null;
    }
    
    // Accessors
    //-----------------------------------------------------------------------
    /**
     * <p>このフォーマッターで使用されるパターンを取得します。
     * {@primary Gets the pattern used by this formatter.}</p>
     * 
     * @return {@link java.text.SimpleDateFormat} と互換性のあるパターン
     * {@primary the pattern, {@link java.text.SimpleDateFormat} compatible}
     */
    public String getPattern() {
        return mPattern;
    }

    /**
     * <p>このフォーマッターで使用されるタイムゾーンを取得します。
     * {@primary Gets the time zone used by this formatter.}</p>
     *
     * <p>このタイムゾーンは常時 <code>Date</code> のフォーマットに使用されます。
     * <code>Calendar</code> がフォーマットのために渡された場合、このタイムゾーンは
     * {@link #getTimeZoneOverridesCalendar()} の結果に応じて使用されます。
     * {@primary This zone is always used for <code>Date</code> formatting.
     * If a <code>Calendar</code> is passed in to be formatted, the
     * time zone on that may be used depending on
     * {@link #getTimeZoneOverridesCalendar()}.}</p>
     * 
     * @return タイムゾーン
     * {@primary the time zone}
     */
    public TimeZone getTimeZone() {
        return mTimeZone;
    }

    /**
     * <p>カレンダーのタイムゾーンがフォーマッターに上書きされる場合、
     * <code>true</code> を返します。
     * {@primary Returns <code>true</code> if the time zone of the
     * calendar overrides the time zone of the formatter.}</p>
     * 
     * @return カレンダーのタイムゾーンがフォーマッターに上書きされる場合、 <code>true</code>
     * {@primary <code>true</code> if time zone of formatter overridden for calendars}
     */
    public boolean getTimeZoneOverridesCalendar() {
        return mTimeZoneForced;
    }

    /**
     * <p>このフォーマッターで使用されるロケールを取得します。
     * {@primary Gets the locale used by this formatter.}</p>
     * 
     * @return ロケール
     * {@primary the locale}
     */
    public Locale getLocale() {
        return mLocale;
    }

    /**
     * <p>このフォーマッターが生成する文字列の最大長の見積もりを返します。
     * {@primary Gets  an estimate for the maximum string length that the
     * formatter will produce.}</p>
     *
     * <p>実際のフォーマットされた文字の長さはほとんどの場合、この長さ以下です。
     * {@primary The actual formatted length will almost always be less than or
     * equal to this amount.}</p>
     * 
     * @return フォーマットされた文字列の最大長
     * {@primary the maximum formatted length}
     */
    public int getMaxLengthEstimate() {
        return mMaxLengthEstimate;
    }

    // Basics
    //-----------------------------------------------------------------------
    /**
     * <p>2つのオブジェクトが等しいかどうか比較します。
     * {@primary Compare two objects for equality.}</p>
     * 
     * @param obj  比較対照となるオブジェクト
     * {@primary the object to compare to}
     * @return 等しい場合、<code>true</code>
     * {@primary <code>true</code> if equal}
     */
    public boolean equals(Object obj) {
        if (obj instanceof FastDateFormat == false) {
            return false;
        }
        FastDateFormat other = (FastDateFormat) obj;
        if (
            (mPattern == other.mPattern || mPattern.equals(other.mPattern)) &&
            (mTimeZone == other.mTimeZone || mTimeZone.equals(other.mTimeZone)) &&
            (mLocale == other.mLocale || mLocale.equals(other.mLocale)) &&
            (mTimeZoneForced == other.mTimeZoneForced) &&
            (mLocaleForced == other.mLocaleForced)
            ) {
            return true;
        }
        return false;
    }

    /**
     * <p>適切なハッシュコードです。{@primary A suitable hashcode.}</p>
     * 
     * @return equals と互換性のあるハッシュコード
     * {@primary a hashcode compatable with equals}
     */
    public int hashCode() {
        int total = 0;
        total += mPattern.hashCode();
        total += mTimeZone.hashCode();
        total += (mTimeZoneForced ? 1 : 0);
        total += mLocale.hashCode();
        total += (mLocaleForced ? 1 : 0);
        return total;
    }

    /**
     * <p>このフォーマッターを説明するデバッグのための文字列
     * {@primary Gets a debugging string version of this formatter.}</p>
     * 
     * @return a debugging string
     */
    public String toString() {
        return "FastDateFormat[" + mPattern + "]";
    }
    
    // Rules
    //-----------------------------------------------------------------------
    /**
     * <p>ルールを定義するインナークラスです。
     * {@primary Inner class defining a rule.}</p>
     */
    private interface Rule {
        int estimateLength();
        void appendTo(StringBuffer buffer, Calendar calendar);
    }

    /**
     * <p>数のルールを定義するインナークラスです。
     * {@primary Inner class defining a numeric rule.}</p>
     */
    private interface NumberRule extends Rule {
        void appendTo(StringBuffer buffer, int value);
    }

    /**
     * <p>単一の決まった文字を出力するインナークラスです。
     * {@primary Inner class to output a constant single character.}</p>
     */
    private static class CharacterLiteral implements Rule {
        private final char mValue;

        CharacterLiteral(char value) {
            mValue = value;
        }

        public int estimateLength() {
            return 1;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            buffer.append(mValue);
        }
    }

    /**
     * <p>決まった文字列を出力するインナークラスです。
     * {@primary Inner class to output a constant string.}</p>
     */
    private static class StringLiteral implements Rule {
        private final String mValue;

        StringLiteral(String value) {
            mValue = value;
        }

        public int estimateLength() {
            return mValue.length();
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            buffer.append(mValue);
        }
    }

    /**
     * <p>値のセットを出力するインナークラスです。
     * {@primary Inner class to output one of a set of values.}</p>
     */
    private static class TextField implements Rule {
        private final int mField;
        private final String[] mValues;

        TextField(int field, String[] values) {
            mField = field;
            mValues = values;
        }

        public int estimateLength() {
            int max = 0;
            for (int i=mValues.length; --i >= 0; ) {
                int len = mValues[i].length();
                if (len > max) {
                    max = len;
                }
            }
            return max;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            buffer.append(mValues[calendar.get(mField)]);
        }
    }

    /**
     * <p>パディングされない数値を出力するインナークラスです。
     * {@primary Inner class to output an unpadded number.}</p>
     */
    private static class UnpaddedNumberField implements NumberRule {
        static final UnpaddedNumberField INSTANCE_YEAR = new UnpaddedNumberField(Calendar.YEAR);
        
        private final int mField;

        UnpaddedNumberField(int field) {
            mField = field;
        }

        public int estimateLength() {
            return 4;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(mField));
        }

        public final void appendTo(StringBuffer buffer, int value) {
            if (value < 10) {
                buffer.append((char)(value + '0'));
            } else if (value < 100) {
                buffer.append((char)(value / 10 + '0'));
                buffer.append((char)(value % 10 + '0'));
            } else {
                buffer.append(Integer.toString(value));
            }
        }
    }

    /**
     * <p>パディングされない月を出力するインナークラスです。
     * {@primary Inner class to output an unpadded month.}</p>
     */
    private static class UnpaddedMonthField implements NumberRule {
        static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
        
        UnpaddedMonthField() {
        }

        public int estimateLength() {
            return 2;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
        }

        public final void appendTo(StringBuffer buffer, int value) {
            if (value < 10) {
                buffer.append((char)(value + '0'));
            } else {
                buffer.append((char)(value / 10 + '0'));
                buffer.append((char)(value % 10 + '0'));
            }
        }
    }

    /**
     * <p>パディングされた数値を出力するインナークラスです。
     * {@primary Inner class to output a padded number.}</p>
     */
    private static class PaddedNumberField implements NumberRule {
        private final int mField;
        private final int mSize;

        PaddedNumberField(int field, int size) {
            if (size < 3) {
                // Should use UnpaddedNumberField or TwoDigitNumberField.
                throw new IllegalArgumentException();
            }
            mField = field;
            mSize = size;
        }

        public int estimateLength() {
            return 4;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(mField));
        }

        public final void appendTo(StringBuffer buffer, int value) {
            if (value < 100) {
                for (int i = mSize; --i >= 2; ) {
                    buffer.append('0');
                }
                buffer.append((char)(value / 10 + '0'));
                buffer.append((char)(value % 10 + '0'));
            } else {
                int digits;
                if (value < 1000) {
                    digits = 3;
                } else {
                    digits = (int)(Math.log(value) / LOG_10) + 1;
                }
                for (int i = mSize; --i >= digits; ) {
                    buffer.append('0');
                }
                buffer.append(Integer.toString(value));
            }
        }
    }

    /**
     * <p>2つの数の数値を出力するインナークラスです。
     * {@primary Inner class to output a two digit number.}</p>
     */
    private static class TwoDigitNumberField implements NumberRule {
        private final int mField;

        TwoDigitNumberField(int field) {
            mField = field;
        }

        public int estimateLength() {
            return 2;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(mField));
        }

        public final void appendTo(StringBuffer buffer, int value) {
            if (value < 100) {
                buffer.append((char)(value / 10 + '0'));
                buffer.append((char)(value % 10 + '0'));
            } else {
                buffer.append(Integer.toString(value));
            }
        }
    }

    /**
     * <p>2つの年の数値を出力するインナークラスです。
     * {@primary Inner class to output a two digit year.}</p>
     */
    private static class TwoDigitYearField implements NumberRule {
        static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
        
        TwoDigitYearField() {
        }

        public int estimateLength() {
            return 2;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
        }

        public final void appendTo(StringBuffer buffer, int value) {
            buffer.append((char)(value / 10 + '0'));
            buffer.append((char)(value % 10 + '0'));
        }
    }

    /**
     * <p>2つの月の数値を出力するインナークラスです。
     * {@primary Inner class to output a two digit month.}</p>
     */
    private static class TwoDigitMonthField implements NumberRule {
        static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
        
        TwoDigitMonthField() {
        }

        public int estimateLength() {
            return 2;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
        }

        public final void appendTo(StringBuffer buffer, int value) {
            buffer.append((char)(value / 10 + '0'));
            buffer.append((char)(value % 10 + '0'));
        }
    }

    /**
     * <p>12時間の時間を出力するインナークラスです。
     * {@primary Inner class to output the twelve hour field.}</p>
     */
    private static class TwelveHourField implements NumberRule {
        private final NumberRule mRule;

        TwelveHourField(NumberRule rule) {
            mRule = rule;
        }

        public int estimateLength() {
            return mRule.estimateLength();
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            int value = calendar.get(Calendar.HOUR);
            if (value == 0) {
                value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
            }
            mRule.appendTo(buffer, value);
        }

        public void appendTo(StringBuffer buffer, int value) {
            mRule.appendTo(buffer, value);
        }
    }

    /**
     * <p>24時間の時間を出力するインナークラスです。
     * {@primary Inner class to output the twenty four hour field.}</p>
     */
    private static class TwentyFourHourField implements NumberRule {
        private final NumberRule mRule;

        TwentyFourHourField(NumberRule rule) {
            mRule = rule;
        }

        public int estimateLength() {
            return mRule.estimateLength();
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            int value = calendar.get(Calendar.HOUR_OF_DAY);
            if (value == 0) {
                value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
            }
            mRule.appendTo(buffer, value);
        }

        public void appendTo(StringBuffer buffer, int value) {
            mRule.appendTo(buffer, value);
        }
    }

    /**
     * <p>タイムゾーンの名称を出力するインナークラスです。
     * {@primary Inner class to output a time zone name.}</p>
     */
    private static class TimeZoneNameRule implements Rule {
        private final TimeZone mTimeZone;
        private final boolean mTimeZoneForced;
        private final Locale mLocale;
        private final int mStyle;
        private final String mStandard;
        private final String mDaylight;

        TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) {
            mTimeZone = timeZone;
            mTimeZoneForced = timeZoneForced;
            mLocale = locale;
            mStyle = style;

            if (timeZoneForced) {
                mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
                mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
            } else {
                mStandard = null;
                mDaylight = null;
            }
        }

        public int estimateLength() {
            if (mTimeZoneForced) {
                return Math.max(mStandard.length(), mDaylight.length());
            } else if (mStyle == TimeZone.SHORT) {
                return 4;
            } else {
                return 40;
            }
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            if (mTimeZoneForced) {
                if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
                    buffer.append(mDaylight);
                } else {
                    buffer.append(mStandard);
                }
            } else {
                TimeZone timeZone = calendar.getTimeZone();
                if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
                    buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
                } else {
                    buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
                }
            }
        }
    }

    /**
     * <p>タイムゾーンを <code>+/-HHMM</code> または <code>+/-HH:MM</code>
     * の数値で出力するインナークラスです。
     * {@primary Inner class to output a time zone as a number <code>+/-HHMM</code>
     * or <code>+/-HH:MM</code>.}</p>
     */
    private static class TimeZoneNumberRule implements Rule {
        static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
        static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
        
        final boolean mColon;
        
        TimeZoneNumberRule(boolean colon) {
            mColon = colon;
        }

        public int estimateLength() {
            return 5;
        }

        public void appendTo(StringBuffer buffer, Calendar calendar) {
            int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
            
            if (offset < 0) {
                buffer.append('-');
                offset = -offset;
            } else {
                buffer.append('+');
            }
            
            int hours = offset / (60 * 60 * 1000);
            buffer.append((char)(hours / 10 + '0'));
            buffer.append((char)(hours % 10 + '0'));
            
            if (mColon) {
                buffer.append(':');
            }
            
            int minutes = offset / (60 * 1000) - 60 * hours;
            buffer.append((char)(minutes / 10 + '0'));
            buffer.append((char)(minutes % 10 + '0'));
        }            
    }

    // ----------------------------------------------------------------------
    /**
     * <p>タイムゾーンの名前のためにキーの混合を行うインナークラスです。
     * {@primary Inner class that acts as a compound key for time zone names.}</p>
     */
    private static class TimeZoneDisplayKey {
        private final TimeZone mTimeZone;
        private final int mStyle;
        private final Locale mLocale;

        TimeZoneDisplayKey(TimeZone timeZone,
                           boolean daylight, int style, Locale locale) {
            mTimeZone = timeZone;
            if (daylight) {
                style |= 0x80000000;
            }
            mStyle = style;
            mLocale = locale;
        }

        public int hashCode() {
            return mStyle * 31 + mLocale.hashCode();
        }

        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj instanceof TimeZoneDisplayKey) {
                TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
                return
                    mTimeZone.equals(other.mTimeZone) &&
                    mStyle == other.mStyle &&
                    mLocale.equals(other.mLocale);
            }
            return false;
        }
    }

    // ----------------------------------------------------------------------
    /**
     * <p>混合オブジェクトを生成するためのヘルパークラスです。
     * {@primary Helper class for creating compound objects.}</p>
     *
     * <p>このクラスの1つの使用方法は、複数のオブジェクトの外にハッシュテーブルのキーを生成することです。
     * {@primary One use for this class is to create a hashtable key
     * out of multiple objects.</p>
     */
    private static class Pair {
        private final Object mObj1;
        private final Object mObj2;

        public Pair(Object obj1, Object obj2) {
            mObj1 = obj1;
            mObj2 = obj2;
        }

        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }

            if (!(obj instanceof Pair)) {
                return false;
            }

            Pair key = (Pair)obj;

            return
                (mObj1 == null ?
                 key.mObj1 == null : mObj1.equals(key.mObj1)) &&
                (mObj2 == null ?
                 key.mObj2 == null : mObj2.equals(key.mObj2));
        }

        public int hashCode() {
            return
                (mObj1 == null ? 0 : mObj1.hashCode()) +
                (mObj2 == null ? 0 : mObj2.hashCode());
        }

        public String toString() {
            return "[" + mObj1 + ':' + mObj2 + ']';
        }
    }

}

