如何映射两个String []彼此 [英] How to map two String[] to each other
问题描述
我开发一个Android应用程序。我映射两个数组给对方一个HashMap中。我改变这些数组转换成String []的,和他们一同映射。它应该返回值,但它返回null。我不知道我要去哪里错了。我在网上搜索,但我还没有发现任何有用的东西。我的code是如下:
I'm developing an Android app. I'm mapping two arrays to each other with a HashMap. I change these arrays into String[]'s, and map them together. It should return values, but it returns null. I'm not sure where I'm going wrong. I've searched online, but I haven't found anything useful. My code is below:
StationList.java部分
Spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String selectedValue = arg0.getItemAtPosition(arg2).toString();
String[] Yellow_ID = getResources().getStringArray(R.array.Yellow_ID);
String[] Yellow_Li = getResources().getStringArray(R.array.Yellow_Line);
Map<String[], String[]> myMap = new HashMap<String[], String[]>();
myMap.put(Yellow_Li, Yellow_ID);
String[] value = myMap.get(selectedValue);
tv12.setText(String.valueOf (value));
}
值
返回在的TextView
空。我认为这是由于没有值映射到对方。我想AP preciate任何帮助,您可以给我。
Value
returns null in the TextView
. I think this is due to the values not mapping to each other. I would appreciate any help you could give me.
推荐答案
根据你如何获取你的价值,你希望你的填充时的HashMap做更多的东西像这样
Based on how you're retrieving your value, you want to do something more like this when populating your hashmap
Map<String, String> myMap = new HashMap<String, String>();
for (int i = 0; i < Yellow_Li.length(); i++) {
myMap.put(Yellow_Li[i], Yellow_ID[i]);
}
String value = myMap.get(selectedValue);
我假设字符串数组的大小相同,所以如果他们不是你应该添加逻辑。
I assume the String arrays are the same size so if they are not you should add that logic in.
此外,如果数组大小都一样,你可以让这样的事情,所以你不必建立一个HashMap:
Also, if the arrays are the same size you could so something like this so you don't have to build a hashmap:
int index = -1;
for (int i = 0; i < Yellow_Li.length(); i++) {
if (Yellow_Li[i].equals(selectedValue)) {
index = i;
break;
}
}
String value = Yellow_ID[index]; //should do a check for -1 before you try to assign "value"
这篇关于如何映射两个String []彼此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!