Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList to Int [] array using .toArray()? Or...?

Tags:

java

arraylist

So, this is part of a method which checks for available rooms within a date range and is meant to return the int [] array of room numbers which are available.

        ArrayList roomNums = new ArrayList();
        roomNums.toArray();
        for (Room room: rooms){
            int roomNumber = room.getRoomNumber();
            if(room.getRoomType() == roomType && isAvailable(roomNumber, checkin, checkout)){ // This works fine, ignore it

                roomNums.add(roomNumber); 
            }
        }
        return roomNums.toArray(); // Error here, return meant to be int [] type but it's java.lang.Obeject []

The error occurs at the end at roomNums.toArray()

I saw someone else do this one liner and it worked for them, why is it not for me?

Every element in roomNums is an integer. (I think)

What's the quickest and easiest way to print an integer array containing the available rooms? Do I need to make a loop or can I do something with this .toArray() one liner or something similar to it?

Thanks

like image 578
Mandingo Avatar asked Oct 23 '25 15:10

Mandingo


1 Answers

Don't use raw types. Replace ArrayList roomNums = new ArrayList(); with

ArrayList<Integer> roomNums = new ArrayList<>();

Then return it as Integer[]

roomNums.toArray(Integer[]::new);

If you need primitive array, then it can be done with stream:

return roomNums.stream().mapToInt(Integer::valueOf).toArray();

See also How to convert an ArrayList containing Integers to primitive int array?

like image 137
Ruslan Avatar answered Oct 26 '25 03:10

Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!