Home > front end >  Java generics - Convert to generics type
Java generics - Convert to generics type

Time:09-26

I am trying out java to create a queue using arrays. It works for a String type and wanted to convert the same code to use generics, to practice generic coding. I am struct where I use streams to print this generic type. Any help?

main method:
QueueArrays queue = new QueueArrays<String>();
queue.enqueue("Jack");
class QueueArrays<T>{
int size;
ArrayList<T> queue;
public QueueArrays(){
    this.queue = new ArrayList<>(10);
    size=0;
}
public QueueArrays enqueue(T value){
    this.queue.add(value);
    size  ;
    return this;
}
   
@SuppressWarnings("unchecked")
public void printQueue(){
 System.out.println(this.queue.stream().collect(Collectors.joining(",", "[", "]")));   
}

How to convert printQueue for generics?

CodePudding user response:

Collectors.joining() requires stream elements, which are CharSequence.

To cite:

Returns: A Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order

So you must either:

  1. Declare bound of the generic type, to be CharSequence
class QueueArrays<T extends CharSequence> {
}
  1. Or map the elements of the stream to a type implementing CharSequence, mapping to String being the easiest
this.queue.stream()
     .map(Object::toString)
     .collect(Collectors.joining(",", "[", "]"));

Additional note, no need to return raw type here:

public QueueArrays enqueue(T value){
    //
}

You should return QueueArrays<T> instead.

  • Related