Search code examples
javastringsublist

subListString Index out of bounds


    horse1ProgressionStr = Integer.toString(horse1Progression);
    horse2ProgressionStr = Integer.toString(horse2Progression);
    horse3ProgressionStr = Integer.toString(horse3Progression);
    horse4ProgressionStr = Integer.toString(horse4Progression);




    List<List<String>> list = Arrays.asList(Arrays.asList(horse1ProgressionStr, horse2ProgressionStr, horse3ProgressionStr, horse4ProgressionStr));
    for (List<String> l : list) {
        Collections.sort(l);
    }
    Collections.sort(list, new Comparator<List<String>>() {
        public int compare(List<String> o1, List<String> o2) {
            return o1.get(0).compareTo(o2.get(0));
        }
    });


    System.out.println("" + list);


    List<List<String>> fourthHorse = list.subList(0, 2);
    List<List<String>> thirdHorse = list.subList(2, 4);
    List<List<String>> secondHorse = list.subList(4, 6);

I have been trying to put 4 ints in order and them put them into separate variables but every way i try it seems to give me a out of bounds exception.

Exception =

Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 2


Solution

  • The code in the question is overly complicated, just do this:

    int[] horses = { horse1Progression, horse2Progression,
                     horse3Progression, horse4Progression };
    
    // sort the input array in ascending order
    Arrays.sort(horses);
    
    // retrieve the elements in each position
    int first  = horses[0];
    int second = horses[1];
    int third  = horses[2];
    int fourth = horses[3];