I do not fully understand how to solve the problem. There is a suspicion that the Queue interface is needed here. Do I think in the right direction?

Implement a class that simulates the work of the n-seat car park. The car pulls up to a certain place and drives to the right until it has a free seat. The class must support the methods that serve the arrival and departure of the car. Determine the method that displays the current parking status in the console.

  • 2
    Enough array. - avp
  • @avp here just want me to add an element to a collection or an array, delete the element and display it on the screen? - user229233
  • It seems to me that yes. Just an array of N elements. 0 - the place is free (at first all are free), 1 - it is occupied. That's all. - avp
  • array of boolean, more convenient to use - V. Makhnutin
  • one
    PriorityQueue fits perfectly, why not use arrays (reinvent the wheel) - GenCloud

1 answer 1

Is this solution right?

public class Task03 { private static Car[] list = new Car[5]; public static void main(String[] args) { Task03 q = new Task03(); add(q.new Car()); add(q.new Car()); add(q.new Car()); add(q.new Car()); add(q.new Car()); add(q.new Car()); print(); remove(1); print(); } public static void add(Car car) { for (int i = 0; i < list.length; i++) { if (list[i] == null) { list[i] = car; return; } } System.out.println("Мест нет!"); } public static void remove(int c) { try { if ((list[c] != null)) { list[c] = null; } else System.out.println("место свободно!"); } catch (IndexOutOfBoundsException e) { System.out.println("такого номера парковки нет!"); } } public static void print() { for (int i = 0; i < list.length; i++) { if (list[i]==null) { System.out.println("Место свободно"); } else System.out.println("Место занято"); } } class Car { } 

}

  • I would not consider this decision. There is a quadratic complexity, but there is a linear solution (or through a heap of at least n log n). - pavel
  • @pavel please explain your comment, what is quadratic complexity and n log n? - user229233
  • @pavel help please - user229233
  • Well, if in a nutshell - the complexity - this is Big-O notation. Using the built-in priority queue as advised to you in the comments will be faster. Or use more efficient algorithms. - pavel