简体   繁体   中英

How can I optimize this android code?

I want to parse jsonarray which has uncertain length,

  • if this array's length is 0,then children are null;
  • if this array's length is 1,then children0 has some value,and others are null;
  • if this array's length is 2,then children0 and children2 have some values, and children3 is null;
  • if this array's length >= 3,then children0 and children1 and children2 have values.

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(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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