Java Map/TreeMap: 修改现有条目而不删除条目

Java Map/TreeMap: Modifying an existing entry without deleting entry

所以我有一个定义为

的地图
Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();

我正在循环读取文本文件时添加数据。对于大部分数据,我将添加它并继续。但是,文件中有一些数据需要应用回现有条目而不删除它或移除它的位置。例子.

data.put(counter, new Object[] {ex1, ex2, ex3, ex4});

所以,如果我要添加一个条目,希望以后有数据,我需要添加(编辑:可以附加),有没有办法保留现有数据并附加新数据?例子.

首先,

data.put(counter, new Object[] {"testData1", "testData2", "testData3", "testData4"});

当我循环到需要添加的数据时,我需要能够将 "testData5" 添加到结束位置,同时只知道最初添加数据时计数器的值。

有没有办法在不删除该特定条目中的现有数据的情况下执行此操作?

编辑:可以附加数据,为此更改示例。

用你的数组,很乱。我同意您应该使用列表的评论,它允许您只使用列表引用而不必在地图上重新设置任何内容。

使用数组(讨厌!)

while(/* fancy argument */) {
    int counter; //you promised me this
    String argument; //and this

    Object[] foo = data.get(counter); //find what is stored on the map  
    Object[] bar; //our expected result

    if(foo == null) { //create a new array and append it
        bar = new Object[1];
        bar[0] = argument;
    }
    else { //fill the new array
        bar = new Object[foo.length+1];
        for(int i = 0; i < foo.length; i++) {
            bar[i] = foo[i];
        }
        bar[foo.length] = argument;
    }

    data.set(counter, bar); //put the updated array into the map
}

使用列表(干净!)

while(/* fancy argument */) {
    int counter; //you promised me this
    String argument; //and this

    List<Object> foo = data.get(counter); //find what is stored on the map  
    //and we don't need bar since we can play with foo

    if(foo == null) { //we have a new list we need to add
        foo = new ArrayList<>();
        data.set(counter, foo); //put it in the map
    }

    foo.add(argument); //add to list, don't need to re-put since it's already there
}