我怎样才能优化这个Android代码?

时间:2016-11-03 05:24:19

标签: java android

我想解析长度不确定的jsonarray,

  • 如果此数组的长度为0,则子项为空;
  • 如果此数组的长度为1,则children0具有某些值,而其他值 是null;
  • 如果此数组的长度为2,则children0和children2有一些 values,children3为null;
  • 如果此数组的长度> = 3,那么children0和children1和 children2有价值。

如何优化此代码?

全部......

这是我第一次提出有关堆栈溢出的问题。

我很抱歉我的英语很差......

String children0 = null;
String children1 = null;
String children2 = null;

if (chArray.length() > 2) {
    children0 = value0;
    children1 = value1;
    children2 = value2;
} else if (chArray.length() == 2) {
    children0 = value0;
    children1 = value1;
} else if (chArray.length() == 1) {
    children0 = value0;
}

2 个答案:

答案 0 :(得分:0)

你可以使用数组

String[] childrens = new String[3];

for(int i=0; i<chArray.length() && i<3; i++)
    childrens[i] = value[i];

答案 1 :(得分:0)

我喜欢switch这个

switch(chArray.length){
    default: // > 2 because every lower cases are defined after!
        children2 = value2;
    case 2:
        children1 = value1;
    case 1:
        children0 = value0;
    case 0: //error check if the array is empty before (this is ugly like this ;) )
}

没有中断,它会根据接收到的数组的长度将自己置于正确的位置,然后执行以下行。

相关问题