简体   繁体   English

如何优化此android代码?

[英]How can I optimize this android code?

I want to parse jsonarray which has uncertain length, 我想解析长度不确定的jsonarray,

  • if this array's length is 0,then children are null; 如果此数组的长度为0,则子级为null;否则,子级为null。
  • if this array's length is 1,then children0 has some value,and others are null; 如果此数组的长度为1,则children0有一些值,其他则为null;
  • if this array's length is 2,then children0 and children2 have some values, and children3 is null; 如果此数组的长度为2,则children0和children2有一些值,children3为null;
  • if this array's length >= 3,then children0 and children1 and children2 have values. 如果此数组的长度> = 3,则children0和children1和children2具有值。

How can I optimize this code? 如何优化此代码?

That's all... 就这样...

It's my first time to ask question on stack overflow. 这是我第一次问堆栈溢出问题。

I'm so sorry for my poor English... 我为我的英语不好对不起...

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;
}

you can use an array 你可以使用一个数组

String[] childrens = new String[3];

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

I like the switch for this 我喜欢这个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 ;) )
}

Without breaks, it will place itself in the right position depending on the length of the array received then execute the following line. 不会中断,它将根据接收到的数组的长度将自己放置在正确的位置,然后执行以下行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM