Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert and cast an object list to an integer list?

Bellow code snippet errors with:

 "Type mismatch: cannot convert from element type Object to Integer".

public static List<Integer> quickSort(List<Integer> arr) {
    if(arr.size() == 1) {
        return arr;
    }
    int mid = arr.size() / 2;
    List left =  Arrays.asList(arr).subList(0, mid);
    List right =  Arrays.asList(arr).subList(mid, arr.size());
    Collections.sort(left);
    Collections.sort(right);
    for (Integer x : left) {
        right.add(x);
    }
    return arr;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There’s a logic bug, Arrays.asList(arr) actually creates a list of lists List<List<Integer>> while it looks like what you want is a List where arr already is one..

Also you need to properly parameterize List left and List right as List<Integer> otherwise it’s treated as default type Object.

public static List<Integer> quickSort(List<Integer> arr) {
    if(arr.size() == 1) {
        return arr;
    }
    int mid = arr.size() / 2;
    List<Integer> left =  arr.subList(0, mid);
    List<Integer> right =  arr.subList(mid, arr.size());
    Collections.sort(left);
    Collections.sort(right);
    for (Integer x : left) {
        right.add(x);
    }
    return arr;
}

EDIT: also returning arr in the return statement means your function does nothing as it just spits out the unedited input.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading