【发布时间】:2017-02-15 11:23:33
【问题描述】:
我在这个论坛和其他论坛上阅读了很多关于此的内容,但我仍然无法得到具体的答案。无论如何,我决定这样做:
这是一个保存字符串和整数的类:
public class Tuple{
private String token;
private int docID;
public Tuple(String token, int docID) {
this.token = token;
this.docID = docID;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getDocID() {
return docID;
}
public void setDocID(int docID) {
this.docID = docID;
}
}
然后,我创建一个数组列表来放置这些元组private ArrayList<Tuple> temps = new ArrayList<>();
然后我像这样填充数组列表:
for ( int i = 0; i < numberOfDocs; i++ )
{
Tuple cat = new Tuple(Double.toString(vect[i]),i);
temps.add(cat);
}
最终,我将数组排序如下:
public void sortTmp()
{
Collections.sort(temps, new Comparator<Tuple>()
{
@Override
public int compare(Tuple tr2, Tuple tr1)
{
return tr2.getToken().compareTo(tr1.getToken());
}
});
}
java 和 doubles 存在一些问题,我不能直接使用我的 double 矩阵,所以我必须这样做 Double.toString() 。结果已排序,但并不完全正确,因为从 double 计算的字符串在 double 数字排序方面不是很准确。
有什么想法吗?
【问题讨论】:
-
按词法排序可能不是您想要的。为什么不能使用双打?或者更好:是什么让你认为你做不到? “java 和 doubles 存在一些问题” - 主要是开发人员遇到了 doubles 而不是 java 的问题。
-
@Fildor 当我将所有内容从
string类型更改为double类型时,此特定行return tr2.getToken().compareTo(tr1.getToken());是错误的。根据我的 IDE:double cannot be dereferenced -
是的,然后更改 that 行,使其适用于双倍。如果需要使用 compareTo,可以使用 Double 包装器。
-
你应该阅读this 解释在原语上调用方法会产生这个问题。使用包装器应该可以解决它
-
例如做
return Double.compare( tr2.getToken(), tr1.getToken() );(当改变getToken()返回double时)
标签: java arrays sorting arraylist