Iterate through string array in Java

后端 未结 10 898
逝去的感伤
逝去的感伤 2020-11-30 01:21

I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first comp

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 02:13

    I would argue instead of testing i less than elements.length - 1 testing i + 1 less than elements.length. You aren't changing the domain of the array that you are looking at (i.e. ignoring the last element), but rather changing the greatest element you are looking at in each iteration.

    String[] elements = { "a", "a","a","a" };
    
    for(int i = 0; i + 1 < elements.length; i++) {
        String first = elements[i];
        String second = elements[i+1];
        //do something with the two strings
    }
    

提交回复
热议问题