TreeMap get獲取資料為null

呂建奎發表於2016-07-16

之前用treeMap進行排序,然後for迴圈keySet,get(Key)獲取到的值是null,後來找到一下方法測了一下,只有沒有註釋的那個方法是可以獲取到值得

public class Test
{

  /**
   * @param args
   */
  public static void main(String[] args)
  {
    Map<Special, List<Integer>> items = new TreeMap<Special, List<Integer>>((Comparator<? super Special>) new Comparator<Special>()
    {
      public int compare(Special special1, Special special2)
      {
        return special2.getIndexNo() < special1.getIndexNo() ? 1 : -1;
      }
    });
    Special a = new SpecialImpl();
    a.setId(1);
    a.setIndexNo(0);
    List<Integer> b = new ArrayList<Integer>();
    b.add(1);
    b.add(2);
    b.add(3);
    items.put(a, b);

    a = new SpecialImpl();
    a.setId(2);
    a.setIndexNo(1);
    b = new ArrayList<Integer>();
    b.add(4);
    b.add(5);
    b.add(6);
    items.put(a, b);

    // Set<Special> keySet = items.keySet(); // keySet獲取key
    // for (Iterator<Special> it = keySet.iterator(); it.hasNext();)
    // {
    // Special special = it.next();
    // System.out.println(special.getId() + "--" + special.getIndexNo() + ":");
    // System.out.println(items.get(special));
    // }
    // 第二種
    Set<Map.Entry<Special, List<Integer>>> entrySet = items.entrySet(); // entrySet獲取對映關係
    Iterator<Map.Entry<Special, List<Integer>>> iter = entrySet.iterator();
    while (iter.hasNext())
    {
      Map.Entry<Special, List<Integer>> me = iter.next();// Map.Entry是entrySet集合的元素型別.
      Special special = me.getKey();
      List<Integer> c = me.getValue();
      System.out.println(special.getId() + "--" + special.getIndexNo() + ":");
      System.out.println(c);
    }
  }

}


相關文章