putExtra treeMap 返回 HashMap 不能转换为 TreeMap android [英] putExtra treeMap returns HashMap cannot be cast to TreeMap android

查看:33
本文介绍了putExtra treeMap 返回 HashMap 不能转换为 TreeMap android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在尝试在 2 个活动之间发送 TreeMap,代码如下:

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

推荐答案

作为@Jave 建议的替代方案,如果您确实需要将数据结构设为 TreeMap,只需使用相应的构造函数即可另一个地图作为数据源.所以在接收端(Two)做这样的事情:

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"));
    }
}

但是,根据您的项目,您可能不必担心确切的 Map 实现.因此,您可以改为转换为 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");
    }
}

这篇关于putExtra treeMap 返回 HashMap 不能转换为 TreeMap android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆