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

Mandingo :

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

Ruslan :

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?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117730&siteId=1