2011-06-08 53 views
4
import java.util.*;  
public class Test { 
     public static void main(String[] args) { 

      Map<String,String> map = new TreeMap<String,String>(); 
      map.put("10", "America"); 
      map.put("1", "Australia"); 
      map.put("2", "India"); 
      map.put("11", "China"); 

      System.out.println(map); 

     } 
    } 

當運行上面的代碼片段,在控制檯我得到的輸出:TreeMap的行爲異常

{1=Australia, 10=America, 11=China, 2=India}

但我期待輸出

{1=Australia, 2=India, 10=America, 11=China}

但是當改變邏輯如所提到的下面內側上述主要()

Map<String,String> map = new TreeMap<String,String>(); 
     map.put("US", "America"); 
     map.put("AUS", "Australia"); 
     map.put("IN", "India"); 
     map.put("CH", "China"); 

    System.out.println(map); 

我得到所期望的輸出

({AUS=Australia, CH=China, IN=India, US=America})

按我理解TreeMap中的的entrySet()方法返回包含在映射的一組視圖地圖。該集的迭代器按照升序鍵順序返回映射。那麼爲什麼在第一種情況下會發生這種情況?

任何建議,非常感謝。

+4

提示:'1 = 「1」' – 2011-06-08 14:56:32

+2

標題是驚人的!幾乎同樣有用:'treemap not works' – bestsss 2011-06-08 15:04:14

+0

對不起,bestsss沒有什麼可以如此認真的 – Neel 2011-06-08 15:16:54

回答

14

因爲"10"字典序比"2"


這裏有一個提示:

Map<Integer,String> map = new TreeMap<Integer,String>(); 
map.put(10, "America"); 
map.put(1, "Australia"); 
map.put(2, "India"); 
map.put(11, "China"); 

System.out.println(map); 
// {1=Australia, 2=India, 10=America, 11=China} 

這裏是另一條線索:String#compareTo(String) VS Integer#compareTo(Integer)


能否請您解釋其實你說的是什麼意思「‘10’排在最後比‘2’小」。

首先,讀取我連接的JavaDoc,特別是第一個鏈接。

現在讓我們回顧一些簡單的字符串比較:

  • 「一」,顯然來之前, 「B」
  • 同樣 「B」 來 「Z」 前

它不應該大部分時間將其擴展爲數字字符:

  • 「0」出現在「1」之前
  • 「1」 來 「9」

單個字符的順序,如abz019被稱爲其lexicographical order之前。總之,每個角色都有一個數字表示,你不會覺得非常驚訝。

現在讓我們來看一些稍微複雜的字符串比較:

  • 「aa」在「BB」(這不應該是太大的驚喜)
  • 「AA」,也談到之前的「前ab「

我們是如何確定第二種情況的?字符的字符。

1. "a" is the same character as "a", so we need to keep going 
2. "a" comes before "b", so we're done. 

再舉一個例子:「ba」在「c」之前,因爲「b」在「c」之前。

讓我們做包含數字字符的字符串同樣的事情:

  • 是否爲 「2」 來了 「10」 之前?我們按字符比較:

    1. 「2」是否在「1」之前?不,它來之後,所以我們已經完成了。
+0

你能解釋一下,你的意思是什麼「10」在詞典上小於'2'「。 – Neel 2011-06-08 15:10:20

+0

在輸入內容時閱讀鏈接的JavaDocs。 – 2011-06-08 15:11:52

+2

正如「BA」小於「C」一樣,「10」小於「2」。在你的情況下,「10」中的「1」小於「2」。 – 2011-06-08 15:15:09