简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM