LinkedHashSet中的唯一Java对象
-
13-11-2019 - |
题
我想创建根据值排序的唯一键值对列表。
我已经尝试创建一个hashmap,但由于我从JSON读取的原始列表被排序HashMap覆盖了最后一个值,以便它们键将具有最小值而不是最大的值。
解决方案是使用LinkedHashSet,以确保唯一性并保持订单。但由于我存储了一个密钥,因此我决定创建一个新类并将它们保存为对象。 我知道我必须实现可比但显然没有比较,而且LinkedHashset不是唯一的。
我的代码是:
public class cellType implements Comparable<Object> {
private String type;
private double confidence;
@Override
public String toString() {
return "type=" + type + " - confidence=" + confidence ;
}
public cellType(String type, double confidence) {
super();
this.type = type;
this.confidence = confidence;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getConfidence() {
return confidence;
}
public void setConfidence(double confidence) {
this.confidence = confidence;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof cellType)) {
return false;
}
cellType ct = (cellType) obj;
return type.equals(ct.getType());
}
@Override
public int compareTo(Object o) {
cellType ct = (cellType) o;
return type.compareTo(ct.getType());
}
.
}
public static void main(String args[]) throws IOException, JSONException {
String freebaseAddress = "https://www.googleapis.com/freebase/v1/search?query=";
System.setProperty("https.proxyHost", "proxy");
System.setProperty("https.proxyPort", "8080");
JSONObject json = readJsonFromUrl(freebaseAddress + "apple");
LinkedHashSet<cellType> rich_types = new LinkedHashSet<cellType>();
JSONArray array = json.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
if (array.getJSONObject(i).has("notable")) {
JSONObject notable = new JSONObject(array.getJSONObject(i)
.getString("notable"));
if (rich_types.size() <= 5)
rich_types.add(new cellType(notable.getString("name"), (Double) array.getJSONObject(i).get("score")));
}
}
System.out.println(rich_types);
}
.
输出是:
[type= monarch - confident= 79.447838,type= monarch - convente= 58.911613,type= monarch - confence= 56.614368,type=创立图 - enfidence= 48.796387,type= politician - confidentce= 38.921349,type=女王联盟 - Confidentce= 36.142864]
解决方案
我认为你的意思是你想使用treemap(map未设置)来使用可比的键对它们进行排序。linkedhashset是一系列元素,这些元素保留了它们的添加顺序。
听起来你想要的是
if (rich_types.size() <= 5) {
cellType ct = new cellType(notable.getString("name"), (Double) array.getJSONObject(i).get("score"));
if(!rich_type.contains(ct))
rich_types.add(ct);
}
. 其他提示
您也需要实现hashcode()。
甚至考虑实现Equals()和hashcode()的人需要至少读取本章有效的java还是更好的整本书。
不隶属于 StackOverflow