Home > Enterprise >  How to convert and cast an object list to an integer list?
How to convert and cast an object list to an integer list?

Time:05-08

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

CodePudding user response:

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.

CodePudding user response:

I really don't know where to start, when I am honest.

First of all: Whatever you're doing here, it is not what I'd call Quicksort - therefore the method name is already misleading. But since you return the source list back anyway and not working on its reference, you're leaving the whole function useless to begin with.

Your error is because lists in Java are parameterised - meaning they need to know the datatype of the entries they will contain. Since everything in Java is a subclass of Object, the "default" type for Lists is Object. That's what the <> next to the datatype is for: to define the type of the List.

So for your example: List<Integer> left, and so on would fix at least the error but not your faulty function. When using Collections.sort you can actually perform it directly on your List, no need to write an own function for it to wrap it.

  • Related