今天优化一段代码,如下
int num = 0; boolean skipAppend = false; int types_ext1[] = new int[] { ModuleType.TYPE_CONTACT, ModuleType.TYPE_MESSAGE, ModuleType.TYPE_PICTURE, ModuleType.TYPE_BOOKMARK,ModuleType.TYPE_MUSIC }; int types_ext2[] = new int[] { ModuleType.TYPE_CONTACT, ModuleType.TYPE_MESSAGE, ModuleType.TYPE_PICTURE, ModuleType.TYPE_BOOKMARK,ModuleType.TYPE_CALENDAR }; int types_ext3[] = new int[] { ModuleType.TYPE_CONTACT, ModuleType.TYPE_MESSAGE, ModuleType.TYPE_PICTURE, ModuleType.TYPE_BOOKMARK };if(mIsGoogleOrigCalendarExist && mIsGoogleOrigMusicExist){ num = types.length; for (int i = 0; i < num; i++) { types_ext[i] = types[i] ; } MyLogger.logE("yjp", "music & calendar are not 3rd-party"); } else if(!(mIsGoogleOrigCalendarExist || mIsGoogleOrigMusicExist)){ num = types_ext3.length; for (int i = 0; i < num; i++) { types_ext[i] = types_ext3[i]; } MyLogger.logE("yjp", "music & calendar are 3rd-party"); } else if(!mIsGoogleOrigCalendarExist && mIsGoogleOrigMusicExist){ num = types_ext1.length; for (int i = 0; i < num; i++) { types_ext[i] = types_ext1[i]; } MyLogger.logE("yjp", "calendar is 3rd-party"); } else if(mIsGoogleOrigCalendarExist && !mIsGoogleOrigMusicExist){ num = types_ext2.length; for (int i = 0; i < num; i++) { types_ext[i] = types_ext2[i]; } MyLogger.logE("yjp", "music is 3rd-party"); }
这段代码,其实就是改变int[]里面的元素。因为int[]数组就是增删比较麻烦,只能靠循环提取到另外的数组。所以,我想到了使用list,这样动态改变起来就非常的方便
如下
ArrayListtypeList = new ArrayList (); for (int i = 0; i < types.length; i++) { typeList.add(types[i]); } try { PackageManager pm1 = getPackageManager(); pm1.getPackageInfo("com.android.calendar", PackageManager.GET_ACTIVITIES); mIsGoogleOrigCalendarExist = true; } catch (PackageManager.NameNotFoundException e) { MyLogger.logE("yjp", "google original Calendar not found"); } try { PackageManager pm2 = getPackageManager(); pm2.getPackageInfo("com.android.music", PackageManager.GET_ACTIVITIES); mIsGoogleOrigMusicExist = true; } catch (PackageManager.NameNotFoundException e) { MyLogger.logE("yjp", "google original Music not found"); } if (!mIsGoogleOrigMusicExist) { typeList.remove(Integer.valueOf(ModuleType.TYPE_MUSIC)); } if (!mIsGoogleOrigCalendarExist) { typeList.remove(Integer.valueOf(ModuleType.TYPE_CALENDAR)); } if (FeatureOption.VANZO_OOS_BROWSER_SUPPORT) { typeList.remove(Integer.valueOf(ModuleType.TYPE_BOOKMARK)); } int num = typeList.size();
在修改的时候,遇到了一个问题,就是当我尝试移除一个名为ModuleType.TYPE_BOOKMARK的元素的时候,我使用的方法是typeList.remove(ModuleType.TYPE_BOOKMARK);结果一直报错,说是数组越界。这个是很容易理解的,因为 ModuleType.TYPE_BOOKMARK本身就是一个数值,代码这时候认为你是移除这个位置上的元素。后来改为这个方法,成功了。另外,这个代码中有一点还是非常值得我们学习的。就是
try { PackageManager pm1 = getPackageManager(); pm1.getPackageInfo("com.android.calendar", PackageManager.GET_ACTIVITIES); mIsGoogleOrigCalendarExist = true; } catch (PackageManager.NameNotFoundException e) { MyLogger.logE("yjp", "google original Calendar not found"); }
它巧妙的运用了异常以后,对接下来try{}代码不做处理的特点,更改了标志位的状态