首先,如果这个问题不恰当,我深表歉意。
我正在我的 Android 应用程序中实现国家/地区选择器功能,并且我找到了一个 github 项目,这对我来说是一个良好的开始。该代码工作正常并且符合预期。
我首先将其分解以了解它是如何工作的。
这是代码中模糊的部分
@Override
protected ArrayList<Country> doInBackground(Void... params) {
ArrayList<Country> data = new ArrayList<Country>(233);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(mContext.getApplicationContext().getAssets().open("countries.dat"), "UTF-8"));
// do reading, usually loop until end of file reading
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
//process line
Country c = new Country(mContext, line, i);
data.add(c);
ArrayList<Country> list = mCountriesMap.get(c.getCountryCode());
if (list == null) {
list = new ArrayList<Country>();
mCountriesMap.put(c.getCountryCode(), list);
}
list.add(c);
i++;
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
//this code enables app to pick the right default country from the spinner
String countryRegion = PhoneUtils.getCountryRegionFromPhone(mContext);
int code = mPhoneNumberUtil.getCountryCodeForRegion(countryRegion);
final ArrayList<Country> list = mCountriesMap.get(code);
/*getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < list.size(); i++)
Toast.makeText(mContext, "ds: " + list.get(i).getName(), Toast.LENGTH_SHORT).show();
}
});*/
if (list != null) {
for (Country c : list) {
if (c.getPriority() == 0 || c.getPriority() == 1) {
mSpinnerPosition = c.getNum();
break;
}
}
}
return data;
}
此代码读取 asset
文件夹中的文件并将对象添加到列表中。
之后,它选择设备的国家/地区并从所有国家/地区的微调器中选择它
在 while
循环中,我认为这行 list.add(c);
没有意义,因为 while 循环将再次循环并创建新的列表对象。如果我注释此行,即使 mCountriesMap
不为 null,mCountriesMap.get(code)
也会返回空列表。
所以我的问题是为什么会发生这种行为? list.add(c);
这里在做什么?
最佳答案
假设有 3 个国家/地区代码 {US,US,AU}。
所以运行它会导致
mCountriesMap{
US: List{US,US}
AU: List{AU}
}
我认为您的疑问是 list.add(c);
在 mCountriesMap.put(c.getCountryCode(), list);
我会尝试一步步解释
第一种情况
ArrayList<Country> list = mCountriesMap.get(US); //No value in mCountriesMap
if (list == null) { //list is null so true
list = new ArrayList<Country>();
mCountriesMap.put(US, list); //mCountriesMap{US: List{} }
}
list.add(US); //mCountriesMap{US: List{US} } here hashmap will get updated
第二种情况
ArrayList<Country> list = mCountriesMap.get(US); //get the prevous list
if (list == null) { //list have value so false
list = new ArrayList<Country>();
mCountriesMap.put(US, list); //mCountriesMap{US: List{US} }
}
list.add(US); //mCountriesMap{US: List{US,US} } here hashmap will get updated
第三个案例只是第一个案例的重复。
关于java - 如何调试这段代码以了解它在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150470/