问题描述
我需要你们的帮助,我不明白发生了什么?
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");
}
}
这篇关于putExtra树形返回HashMap中不能被转换为TreeMap的机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!