2012-03-29 30 views
0

我希望能夠根據它們輸入到Map中的哪一天對文件進行排序。關鍵是當天,並且值是在相應日期添加的n個文件的列表。但是,我需要能夠將文件一次添加到列表中,但我一直在語法上。如何從Map.put()中調用List.add()?這是我的代碼:將單個元素添加到NavigableMap中的列表

public static NavigableMap<String, List<File>> myFiles = new TreeMap<>(); 
String today = new Date().toString(); 
File currentFile; 
myFiles.put(today, currentFile); //problem here adding currentFile 
+0

您必須檢查是否有列表已經存在。或者使用來自Guava或Apache Commons Collections的'MultiMap'。 – biziclop 2012-03-29 15:16:19

+0

我真的不清楚你在問什麼...... – 2012-03-29 15:17:58

+0

我需要多個文件來共享NavigableMap中的同一個鍵,但我想一次添加一個文件,因爲它們是創建的,而不是一個在一天結束時收集。 – Ted 2012-03-29 15:27:36

回答

1

這是因爲類型安全(使用泛型)。 today指向文件列表,並且您只想將一個文件添加到該列表。

我建議你先檢查是否today是在地圖,如果不加後臺列表,然後,添加currentFile到該列表:

if (!myFiles.containsKey(today)) 
    myFiles.put(today, new ArrayList<File>()); 

myFiles.get(today).add(currentFile); 
1

你應該有兩個層次,所以首先檢查當天是否已經有一個列表,否則你創建一個空列表並將它添加到集合中。

void addFile(File file) 
{ 
    String today = new Date().toString(); 
    List<File> listForDay = myFiles.get(today); 

    // if there are no files for today then create and empty list for the day 
    if (listForDay == null) 
    { 
    listForDay = new ArrayList<File>(); 
    myFiles.put(today, listForDay); 
    } 

    listForDay.add(file); 
}