Ranit Bagchi
Ranit Bagchi

Reputation: 23

Java error java: incompatible types: void cannot be converted to java.util.List<java.lang.Integer> when trying to sort list using Collections.sort()

I am trying to return the sorted version of arrnew but it keeps giving me an error on the part Collections.sort(arrnew). My goal of this code is to accept a variable n .I find all factorial numbers of n and find prime factors of those numbers and add it to the array.

import java.util.List;
import java.util.*;
import java.io.*;
public class test2 {
    public static List<Integer> factorFactorial(int n) {
        ArrayList<Integer> arrnew = new ArrayList<>();
        while(n>0) {
            int x=n;
            for (int i = 2; i <= x ; i++) {
                while (x % i == 0) {
                    arrnew.add(i);
                    x = x / i;
                }
            }
            n--;
        }
        ;
        return Collections.sort(arrnew);
    }
    public static void main(String[] args) {
        List<Integer>a=factorFactorial(10);
        for(int x:a){
            System.out.print(x);
        }
    }
}

Upvotes: 0

Views: 1821

Answers (2)

azro
azro

Reputation: 54168

The Collections.sort signature is public static <T extends Comparable<? super T>> void sort​(List<T> list), so as it is void it doesn't return the given list, you have to split it in

Collections.sort(arrnew)
return arrnew;

Or using Stream you can inline it and return a new list object

return arrnew.stream().sorted().collect(Collectors.toList());

Upvotes: 1

Hedley
Hedley

Reputation: 1112

Collections.sort() returns void, but you have specified your method should return a list. You can simply change your code to return the sorted list:

Collections.sort(arrnew)
return arrnew;

Upvotes: 4

Related Questions