putExtra树形返回HashMap中不能被转换为TreeMap的机器人转换为、机器人、putExtra、HashMap

2023-09-04 11:28:10 作者:心事死在風裏

我需要你们的帮助,我不明白发生了什么?

I need your help, I cannot understand what's happening?

我想2活动之间发送的TreeMap中,code是这样的:

I'm trying to send a TreeMap between 2 activities, the code is something like this:

class One extends Activity{
 public void send(){
   Intent intent = new Intent(One.this, Two.class);
   TreeMap<String, String> map = new TreeMap<String, String>();
   map.put("1","something");
   intent.putExtra("map", map);
   startActivity(intent);
   finish();
 }
}

class Two extends Activity{
  public void get(){
  (TreeMap<String, String>) getIntent().getExtras().get("map");//Here is the problem
  }
}

这回到了我的HashMap不能被转换为TreeMap中。什么

This returns to me HashMap cannot be cast to TreeMap. What

推荐答案

作为替代@ java的的建议,如果你真的需要的数据结构是一个 TreeMap的,只是使用适当的构造函数,另一个地图作为数据源。所以在接收端(两个)做这样的事情:

As alternative to @Jave's suggestions, if you really need the data structure to be a TreeMap, just use the appropriate constructor that takes another map as data source. So on the receiving end (Two) do something like:

public class Two extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TreeMap<String, String> map = new TreeMap<String, String>((Map<String, String>) getIntent().getExtras().get("map"));
    }
}

不过,这取决于你的项目,你可能不担心确切地图的实施。因此,在代替,你可以只转换为地图接口:

However, depending on your project, you probably don't have to worry about the exact Map implementation. So in stead, you could just cast to the Map interface:

public class Two extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Map<String, String> map = (Map<String, String>) getIntent().getExtras().get("map");
    }
}