putExtra treeMap returns HashMap cannot be cast to TreeMap android

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

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
  }
}

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


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

Sounds like it serializes to a HashMap and that's what you're getting. Guess you're gonna have to settle for a HashMap. Alternatively you can create your own helper class and implement Parcelable, then serialize the key/strings in order.


不用直接将结果转换为TreeMap ,您可以创建一个新的TreeMap<String, String>并使用putAll()方法:

TreeMap<String, String> myMap = new TreeMap<String, String>;
HashMap<String, String> receivedMap = getIntent().getExtras().get("map");
myMap.putAll(receivedMap);
链接地址: http://www.djcxy.com/p/11642.html

上一篇: SCons生成可变数量的目标

下一篇: putExtra treeMap返回的HashMap不能转换为TreeMap android