Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java generics – Convert to generics type

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading