简体   繁体   English

可实例化的Java通用 <E extends Comparable<E> &gt;

[英]An instantiable Java generic for <E extends Comparable<E>>

I have a class (let's say a trolley [aka. "cart" in en-US]) that loads a bunch of objects that are either strings or integers. 我有一个类(假设是手推车,在英语中也称为“购物车”),该类加载一堆字符串或整数的对象。 The users specifies as input a flag to state how the input should be read. 用户指定一个标志来声明应如何读取输入。 The trolley class only cares that the objects are comparable for sorting. 手推车类只关心对象在分类方面是可比的。 However, I'm having trouble reusing the same trolley object for both string and integers. 但是,我在为字符串和整数重用同一手推车对象时遇到了麻烦。 To explain, here is an MWE: 为了解释,这是一个MWE:

import java.util.TreeSet;

public class Trolley<E extends Comparable<E>> {
    public TreeSet<E> items;

    public Trolley(){
        items = new TreeSet<E>();
    }

    public boolean addItem(E item){
        return items.add(item);
    }

    public static void main(String args){
        // read from input
        boolean numeric = false;

        Trolley<?> items = null;
        if(numeric)
            items = new Trolley<Integer>();
        else items = new Trolley<String>();

                // items will be parsed from a file
        if(numeric){
                        // compiler warning about generic mismatch
            items.addItem(42);
        } else{
                        // compiler warning about generic mismatch
            items.addItem("42");
        }
    }
}

This gives compiler warnings on the addItem(.) calls. 这会在addItem(.)调用中给出编译器警告。

The trolley will only ever sort the items and print them as strings (ie, whether the input was numeric or string, the subsequent code will not care). 手推车只会对项目进行分类并将其打印为字符串(即,无论输入是数字还是字符串,后续代码都不会在意)。

Again this is just an MWE-like analogy of what I want to do (in reality, I want to load a directed graph into memory and loading integers is to save memory if the input has optionally been dictionary encoded beforehand). 同样,这只是我想要做的一个类似于MWE的类比(实际上,如果输入事先经过字典编码,我想将有向图加载到内存中,并且加载整数是为了节省内存)。


My question is how can I configure the generics to permit use of the same trolley object to abstract integer and string input? 我的问题是如何配置泛型以允许使用同一手推车对象来提取整数和字符串输入?

I've tried a few things such as the above wildcard and such as Trolley<? extends Comparable<?>> items = new Trolley<? extends Comparable<?>>() 我已经尝试了一些方法,例如上述通配符和Trolley<? extends Comparable<?>> items = new Trolley<? extends Comparable<?>>() Trolley<? extends Comparable<?>> items = new Trolley<? extends Comparable<?>>() Trolley<? extends Comparable<?>> items = new Trolley<? extends Comparable<?>>() but that didn't work either. Trolley<? extends Comparable<?>> items = new Trolley<? extends Comparable<?>>()但这也不起作用。 I guess intuitively the problem here is that I could add any objects to the Trolley that may not be comparable with each other like a mix of strings and integers whereas I would like a Trolley object that would accept only one type of Comparable ... but any type.) 我直觉地猜想这里的问题是我可以将任何可能无法相互比较的对象添加到Trolley ,例如字符串和整数的混合,而我想要一个只接受一种类型的ComparableTrolley对象...但是随便哪种。)

(EDIT: I should add, I would prefer to avoid using a wrapper class like Item since this code will be memory constrained.) (编辑:我应该补充,我宁愿避免使用像Item这样的包装器类,因为此代码将受到内存限制。)

A Trolley<?> is a Trolley of a specific type but we don't know which type. Trolley<?>是特定类型的Trolley ,但我们不知道哪种类型。

It happens that in your code it may well be a Trolley<Integer> or a Trolley<String> . 碰巧在您的代码中它很可能是Trolley<Integer>Trolley<String>

So the compiler can't let you add anything but null to that trolley because its actual type will only be determined at runtime. 因此,编译器不允许您向该手推车添加除null任何内容,因为其实际类型仅在运行时确定。

To make your code compile without too many changes you need to have one branch for Integer and one for String: 要使代码无需太多更改即可编译,您需要为Integer设置一个分支,为String设置一个分支:

public static void main(String args) {
  boolean numeric = false;

  if (numeric) {
    Trolley<Integer> trolley = new Trolley<>();
    trolley.addItem(42);
  } else {
    Trolley<String> trolley = new Trolley<>();
    trolley.addItem("42");
  }
}

The final solution I used (inspired by @assylias' answer): 我使用的最终解决方案(受@assylias的回答启发):

public static void main(String args) {
  boolean numeric = false;

  Trolley<? extends Comparable<?>> trolley = null;
  if (numeric) {
    Trolley<Integer> trolleyN = new Trolley<Integer>();
    trolleyN.addItem(42);
    trolley = trolleyN;
  } else {
    Trolley<String> trolleyS = new Trolley<String>();
    trolleyS.addItem("42");
    trolley = trolleyS;
  }

  // use trolley in "read-only" mode
}

暂无
暂无

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

相关问题 如何使用扩展类 <E extends Comparable<E> &gt; - How to extend Generic abstract Class with <E extends Comparable<E>> Java Generics E扩展了Comparable <E> 留下警告 - Java Generics E extends Comparable<E> leaves warning 声明迭代器 <? extends E & Comparable<? super E> &gt; Java中的迭代器 - declaring Iterator<? extends E & Comparable<? super E>> iterator in java 如何创建E类型的Java列表扩展Comparable <? super E> - How to create Java List of Type E extends Comparable<? super E> 公共接口ITMark <E extends Comparable<E> &gt; - public interface ITMark<E extends Comparable<E>> Java通用接口扩展了Comparable - Java generic interface extends Comparable Java泛型:Comparable类型的compareTo(capture#2-of?扩展E)方法不适用于自变量(Comparable) - Java Generics :The method compareTo(capture#2-of ? extends E) in the type Comparable is not applicable for the arguments (Comparable) JAVA:绑定不匹配:不是有界参数的有效替代 <E extends Comparable<E> &gt; - JAVA : Bound mismatch: is not a valid substitute for the bounded parameter <E extends Comparable<E>> Java Generics - 绑定不匹配:类型 Object 不是绑定参数的有效替代品<e extends comparable<e> &gt;</e> - Java Generics - Bound mismatch: The type Object is not a valid substitute for the bounded parameter <E extends Comparable<E>> Java递归通用模板:这是什么意思……S扩展了Writer <E> &gt;扩展实体 <E,S> - Java Recursive generic template: what does this mean by … S extends Writer<E>> extends Entity<E,S>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM