首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型Java超级

泛型Java超级
EN

Stack Overflow用户
提问于 2013-04-10 19:37:14
回答 4查看 229关注 0票数 1

下面代码中的listNum.add(数字)有什么问题;(Reference- http://docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html)

它给出了编译错误,因为方法add(捕获#1-of?超长)不适用于参数(数字)

代码语言:javascript
复制
public class GenericSuper {

   List<? super Long> listNum = new LinkedList < Number >();
   List<? super ExportException> listExp= new LinkedList<RemoteException>();

   public List<? super ExportException> addList()
   {
      Number num = 10;
      listNum.add(num);
      RemoteException rme = new RemoteException();
      listExp.add(rme);
      return rme;
   }
}
EN

回答 4

Stack Overflow用户

发布于 2013-04-10 19:48:56

listNum可能是List<Long>的一个实例,您不能将Number添加到Long列表中,因为它会抛出类类型转换异常。

解决方案:

Long

  1. make a listNum a
    1. alistNuma
      1. alistNuma
        1. alistNuma
          1. aLong
票数 1
EN

Stack Overflow用户

发布于 2013-04-30 11:03:46

代码语言:javascript
复制
package main.java.com.mysystems.generics;

import java.rmi.RemoteException;
import java.rmi.server.ExportException;
import java.rmi.server.SocketSecurityException;
import java.util.LinkedList;
import java.util.List;

//peCS
//Consumer super- you want to add item i.e of super type to the collection.
public class GenericSuper {


    List<? super Long> listNum = new LinkedList < Number >();// listNum is variable that can be assigned list of type super class to Long.
    //And you can put Long and its subclass. And you can only get Object type since it can hold anything from Long to Object.

    List<? super ExportException> listExp= new LinkedList<RemoteException>(); // listExp is variable that can be assigned any list of type super class to ExportException. 
    // And you can  put ExportException and all subclasses of ExportException to the list. And you can only get Object type since it can hold anything from ExportException to Object.

    public List<? super ExportException> addList()
    {
        LinkedList < Number > numList = new LinkedList < Number >();

        Number num = 10.10;
        numList.add(num);
        listNum = numList;
        //listNum.add(num); //Compilation error as only long or its subclass can be added.
        listNum.add(20L);

        for(Object e:listNum){ // Note you can only get Object type and will have to use instance of to do anything meaningful.
            System.out.println(e);
        }
        SocketSecurityException sse = new SocketSecurityException("Hello");
       listExp.add(sse);
       return listExp;
       }
   }
票数 0
EN

Stack Overflow用户

发布于 2015-09-07 16:13:59

问题不在于泛型的实现,而在于它是一个基本的Java Collection框架错误,在这个错误中你不能将Number类型添加到Long type.Generics中,只是在编译time.Had泛型时不在这个地方解决它,你会得到运行时异常,即ClassCastException。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15924770

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档