简体   繁体   English

Java generics - 转换为 generics 类型

[英]Java generics - Convert to generics type

I am trying out java to create a queue using arrays.我正在尝试 java 使用 arrays 创建队列。 It works for a String type and wanted to convert the same code to use generics, to practice generic coding.它适用于 String 类型,并希望将相同的代码转换为使用 generics 来练习通用编码。 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?如何为 generics 转换 printQueue?

Collectors.joining() requires stream elements, which are CharSequence . Collectors.joining()需要 stream 元素,即CharSequence

To cite:引用:

Returns: A Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order返回: 一个收集器,它连接 CharSequence 元素,由指定的分隔符分隔,按照遇到的顺序

So you must either:因此,您必须:

  1. Declare bound of the generic type, to be CharSequence将泛型类型的边界声明为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或 map 将 stream 的元素转换为实现CharSequence的类型,映射到String是最简单的
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.您应该改为返回QueueArrays<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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