在TreeMap中查找某个值并保存

问题描述 投票:2回答:1

我在保存一些我想在TreeMap中寻找的信息时遇到了麻烦。 TreeMap(tm)有一个字符串作为键,一个TreeSet(无关紧要的对象)作为值。我想找到一个特定的键,然后将TreeSet存储在一个变量中以便以后使用它。我该怎么做?

它弹出一个错误,说“类型不匹配:无法从Object转换为TreeSet”

正如它在equals中的情况一样。

import java.util.*;

class ArbolS extends Arbol{
   private TreeMap<String, TreeSet<PLoc>> tm;

  public ArbolS(){
    tm = new TreeMap<String, TreeSet<PLoc>>();
  }

  public boolean Insert(PLoc p){
    boolean found = false;
    Set it = tm.entrySet();
    Iterator iterator = it.iterator();
    Map.Entry mentry;
    TreeSet<PLoc> aux;

    while(iterator.hasNext() || found){
      mentry = (Map.Entry)iterator.next();
      if(mentry.getKey().equalsIgnoreCase(p.getPais())){
        found = true;
        aux = mentry.getValue(); //Error here
      }
    }
  }
}
java treemap type-mismatch treeset
1个回答
4
投票

您应该使用参数化类型替换所有原始类型:

public boolean Insert(PLoc p){
    boolean found = false;
    Iterator<Map.Entry<String, TreeSet<PLoc>>> iterator = tm.entrySet().iterator();
    TreeSet<PLoc> aux;
    while (iterator.hasNext() && !found) {
        Map.Entry<String, TreeSet<PLoc>> mentry = iterator.next();
        if(mentry.getKey().equalsIgnoreCase(p.getPais())) {
            found = true;
            aux = mentry.getValue();
        }
    }
}

请注意,我也将条件|| found更改为&& !found。如果iterator.hasNext()返回false,你不能留在循环中,并且看起来你想在找到第一场比赛后退出循环。

© www.soinside.com 2019 - 2024. All rights reserved.