3

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

Matt
  • 809
  • 1
  • 10
  • 22
  • 3
    Also see [What is a raw type and why shouldn't we use it](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – azurefrog Mar 14 '19 at 21:42
  • 4
    [How to convert List to int[\] in Java?](https://stackoverflow.com/q/960431) – Pshemo Mar 14 '19 at 21:48

3 Answers3

5

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?

Ruslan
  • 6,090
  • 1
  • 21
  • 36
1

Unfortunately, you will need to use Integer[] if you want to use toArray

    List<Integer> roomNums = new ArrayList<>();
    // code here
    Integer[] arr = new Integer[roomNums.size()];
    return roomNums.toArray (arr);

However you can still do it manually like

    List<Integer> roomNums = new ArrayList<> ();
    // code here
    int[] arr = new int[roomNums.size()];
    for (int i = 0; i < arr.length; i++)
        arr[i] = roomNums.get (i);
    return arr;
alvinalvord
  • 394
  • 2
  • 11
0

As mentioned above use the ArrayList to hold your values:

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

then you can use the object super class to convert to array

   Object[] numbersArray = roomNums.toArray();

then just continue running the for loop and your program