A
A
Alex2018-02-21 18:26:09
Java
Alex, 2018-02-21 18:26:09

How can we improve the Queue class so that other types of data can be stored in the queue, such as values ​​of type int or double?

How can we improve the Queue class so that other types of data can be stored in the queue, such as values ​​of type int or double?

public class Queue {
  
  char q[]; // Array to storage elements in queue	
  int putloc, getloc;
  
  // indexes of placement and extracting  queue elements
  
  Queue(int size) { q = new char[size+1];
  
  // allocate memory for queue
  
  putloc = getloc = 0; }
  
  // put symbol in queue
  
  void put(char ch) {
    if(putloc==q.length-1) {
      System.out.println(" - Queue is full.");
      return; }
    putloc++;
    q[putloc] = ch; }
  
  // extract symbol from the queue
  
  char get() { 
    if(getloc == putloc) { 
      System.out.println(" - Queue is empty."); 
      return (char) 0; } 
    getloc++;
    return q[getloc]; 
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-02-21
@cocaine4ik

Namely int, double, float, char, byte, long, short - no way. Even though Java is OOP, these types are not objects. They are not inherited from Object'a, they do not have a common ancestor. Therefore, generics do not work for them.
You can use the boxed types Integer, Double, Float, etc. Then one can generalize the queue type in the spirit

class Queue <T> {
    private T[] q;
   ...
}
...
Queue<Integer> = new Queue<>();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question