英文:
How does Treemap works?
问题
所以我试图从一个Excel文件中读取数据,我使用Treemap来读取文件。但问题是,treemap将我的数据随机放入它的列表中。尽管我在使用它时设置了索引。
//这段代码从旧文件中写入数据
//writer是我的Treemap
//sReadData是包含旧数据的列表
for (int i = 0; i < (sReadData.size() + 1) / 5; i++) {
writer.put(String.valueOf(i), new Object[] { sReadData.get(i * 5), sReadData.get(i * 5 + 1), sReadData.get(i * 5 + 2), sReadData.get(i * 5 + 3), sReadData.get(i * 5 + 4)});
}
writer.put(String.valueOf(iCounter + 1), new Object[] { "Name", "Date", "Time", "Type", "Owner" });
//这段代码写入新数据
for (int i = 0; i < sName.length; i++) {
//iCounter只是旧文件中的行数|这些只是包含一些数据的数组
writer.put(String.valueOf(iCounter + 2 + i), new Object[] { sName[i], sDate[i], sTime[i], sTypes[i], sOwners[i] });
}
我的错误在于我错误地初始化了我的Treemap。它应该像这样:Map<Integer, Object[]> tMap = new TreeMap<Integer, Object[]>();
。
英文:
So I'm trying to read data from an excel file and I use Treemap to read the file. But the problem is that treemap puts my data random into its list. Although, I set an index when I use it.
//This writes the data from an old file
//writer is my treemap
//sReadData is a List with the old data
for (int i = 0; i < (sReadData.size()+1)/5; i++) {
writer.put(String.valueOf(i),new Object[] { sReadData.get(i*5),sReadData.get(i*5+1),sReadData.get(i*5+2),sReadData.get(i*5+3),sReadData.get(i*5+4)});
}
writer.put(String.valueOf(iCounter +1), new Object[] { "Name", "Date","Time", "Type","Owner"});
//This writes the new data
for (int i = 0; i < sName.length; i++) {
//iCounter is just the number of rows from the old file|These are just some Array with some data
writer.put(String.valueOf(iCounter+2+i), new Object[] { sName[i], sDate[i],sTime[i], sTypes[i],sOwners[i]});
}
My mistake was that I initialized my treemap wrong. It should be like this: Map<Integer, Object[]> tMap = new TreeMap<Integer, Object[]>();
答案1
得分: 1
订单不会随机排列。但可能不符合您的期望。字符串按词典顺序排列,所以 "1" < "10" < "100" < ... < "11" ... < "2"。
如果您希望TreeMap
条目以数字顺序返回,请将键类型设置为Integer
。
当我尝试使用
int
而不是String
时,我收到以下错误消息:The method put(String, Object[]) in the type Map<String,Object[]> is not applicable for the arguments (int, Object[])
您还需要更改地图的声明为TreeMap<Integer, Object[]>
。
英文:
The order won't be random. But it may not be what you expect. Strings are ordered lexically, so that "1" < "10" < "100" < ... < "11" ... < "2".
If you want the TreeMap
entries to be returned in numerical order, use Integer
as the key type.
> When I try to use an int
instead of a String
, I get this error:
>
> The method put(String, Object[]) in the type Map<String,Object[]>
> is not applicable for the arguments (int, Object[])
You also need to change the declaration of the map to TreeMap<Integer, Object[]>
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论