0

I am tring to print N to 1 using recursion. But while doing so I am getting the following errors what should I change in the code to convert the ArrayList to array successfully

Here is the Code-->

import java.util.ArrayList;
class HelloWorld {
    static ArrayList<Integer> ar = new ArrayList<>();
    public static int[] printNos(int x) {
        // Write Your Code Here
        if(x>0){
            ar.add(x);
            printNos(x-1);
        }
        int [] arr = new int[ar.size()];
        arr = ar.toArray(arr);
        return arr;

    }
    public static void main(String[] args) {
        int [] ark = printNos(5);
        for(Interger e: ark){
            System.out.print(e);
        }
    }
}

and the following error is occuring-->

ERROR!

javac /tmp/kEUqQIfOZV/HelloWorld.java
/tmp/kEUqQIfOZV/HelloWorld.java:11: error: no suitable method found for toArray(int[])
        arr = ar.toArray(arr);
^
    method Collection.<T#1>toArray(IntFunction<T#1[]>) is not applicable
      (cannot infer type-variable(s) T#1
        (argument mismatch; int[] cannot be converted to IntFunction<T#1[]>))
    method ArrayList.<T#2>toArray(T#2[]) is not applicable
      (inference variable T#2 has incompatible bounds
        equality constraints: int
        lower bounds: Object)
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>toArray(IntFunction<T#1[]>)
    T#2 extends Object declared in method <T#2>toArray(T#2[])
/tmp/kEUqQIfOZV/HelloWorld.java:18: error: cannot find symbol
        for(Interger e: ark){
            ^
symbol:   class Interger
  location: class HelloWorld
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors

Here I know that the second Error is occuring due to the first and I can also solve this problem using various other methods but what I want to learn is why the ArrayList in this code is not converted in array and throws the Error and what changes i have to do to avoid this error ?

0

4 Answers 4

2

The problem is:

    int [] arr = new int[ar.size()];
    arr = ar.toArray(arr);
             ^^^^^^^

toArray is defined as:

<T> T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

so it uses java generics, generics work on Object types not primitives, so T cannot be int.

To fix it you may change int [] to Integer [] in your code. Or use some idiomatic conversion code like in this answer: How to convert an ArrayList containing Integers to primitive int array?

... and your second error is a typo:

for(Interger e: ark){
        ^ ~~~~ !
0
1

ArrayList are part of Collection framework in Java. arrayList.toArray() method returns array of Object type which can be any type of Wrapper classes in Java.

Answer: You're trying to assign output of toArray() method to a primitive type (int[]) which is causing the error. Using wrapper class Integer would fix the first error. Second error is just a typo.

0

The following Code worked for me for the above code

int [] arr = ar.stream().mapToInt(i -> i).toArray();

For converting a ArrayList To Array

0
  1. 1st Error : You have written toArray method in a wrong way. T[] toArray(T[] a) allows Generic type array only as an argument and as of now Generic type doesn't work for primitive data types.

  2. 2nd Error : This is just a typo issue, not happening due to the previous error. It's Integer not Interger.

  3. Suggestion : why to return an primitive array? when you already have the desired output in the list itself! You can simply print that data, why complicate things ?

import java.util.ArrayList;
class HelloWorld {
    static ArrayList<Integer> ar;
    public static void printNos(int x) {
        // Write Your Code Here
        if(x>0){
            ar.add(x);
            printNos(x-1);
        }

    }
    public static void main(String[] args) {
        ar = new ArrayList<>();
        printNos(5);
        for(Integer e: ar){
            System.out.print(e + " ");
        }
    }
}
  1. Update As Per comment : If you learning List to Array conversion, just use Integer[], or you can go with stream or simple for loop too. Also don't follow this format of code. Here you are unnecessarily creating new int[] objects of size n in every recursion function. Just move your List to Array convertion code inside your main function. That will just create the object only once.(better memory management)
6
  • You are right but I want to understand and learn how to convert an ArrayList to Array Commented Jan 21, 2024 at 12:13
  • 1
    @Ayush, check this - stackoverflow.com/questions/9572795/… Commented Jan 21, 2024 at 12:18
  • print(e) will concatenate all elements ... you probably want to add a space character or comma
    – user85421
    Commented Jan 21, 2024 at 12:29
  • @user85421, thanks for the suggestion. I just went with whatever format Ayush is using in his code. Commented Jan 21, 2024 at 12:31
  • 1
    I just went by common sense, assuming that posted code never generated any output, so posted format was never verified; and that the author of this question or whoever is having similar problem is more inclined to see separated numbers.
    – user85421
    Commented Jan 21, 2024 at 12:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.