简体   繁体   English

为什么我不能将通用类型参数添加到ArrayList中?

[英]Why cant i add a generic type parameter into an ArrayList?

The code below on the first commented line says "City cannot be converted to T". 下面第一行注释中的代码显示“城市无法转换为T”。 So on the next line, i casted it to T. After compiling the method "testing" in the main program it throws this exception: "Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lapi.xapi.City;" 因此,在下一行中,我将其强制转换为T。在主程序中编译方法“ testing”后,它将引发以下异常:“线程“ main”中的异常java.lang.ClassCastException:[Ljava.lang.Object;不能是强制转换为[Lapi.xapi.City;“

Can anyone explain why this happens and get a solution if possible? 谁能解释为什么会这样,并在可能的情况下找到解决方案?

Thanks in advance. 提前致谢。

By the way, i need to acess some methods from City class in MyMap class and i can only use casts if there's really no other way. 顺便说一句,我需要从MyMap类中的City类访问一些方法,并且我只能在没有其他方法的情况下使用强制类型转换。

public class MyMap <T extends City> extends DirectedGraph<City> {

    public void add(T vertex) {
      super.addVertex(vertex);
    }

    public void testing(T vertex) {
      ArrayList<T> x = new ArrayList<>();
    //x.add(super.vertices[0]);        
      x.add((T) super.vertices[0]);
    } 
}

------------------------------------------------------------------------------------------ -------------------------------------------------- ----------------------------------------

Info Update: Sorry for the lack of info. 信息更新:很抱歉缺少信息。

This is superclass DirectedGraph: 这是超类DirectedGraph:

public class DirectedGraph<T>{

protected final int DEFAULT_CAPACITY=15;
protected T[] vertices;
protected double[][] edges;
protected int numVertices;

public DirectedGraph() {
    this.vertices = (T[]) (new Object[DEFAULT_CAPACITY]);
    this.edges = new double[DEFAULT_CAPACITY][DEFAULT_CAPACITY];
}

public void addVertex(T vertex) {
    this.vertices[this.numVertices] = vertex;
    this.numVertices++;
}
}

You have limited T to subtypes of City, I am guessing that super.vertices is either return a super type of city or Object. 您将T限制为City的子类型,我猜测super.vertices返回的是City或Object的超级类型。 By casting to T you are telling the compiler "trust me I know it's a subtype of City" 通过强制转换为T,您告诉编译器“相信我,我知道它是City的子类型”

Please consider some of the corrections as posted as a comment on your Question. 请考虑发布的一些更正,作为对您的问题的评论。

I assume that the main body can look like something like this: 我假设主体看起来像这样:

public static void main(String args[]) {
  new MyMap<City>().testing(new City());
}

Then, as to why 'casting to T fails': 然后,关于“向T广播失败”的原因:

When you instantiate new MyMap<City>() , it effectively tries to create an City [] , but you assign it an Object [] . 实例化new MyMap<City>() ,它实际上会尝试创建City [] ,但是将其分配给Object [] The compiler allows this, because with Generics and Type erasure, nothing is wrong at this point. 编译器允许这样做,因为在使用泛型和类型擦除时,此时没有错误。 The compiler just doesn't know yet that it could get anything other than Object [] assigned. 编译器只是不知道它可以得到除Object []之外的任何东西。

A couple of solutions can be offered, all of them question if you shouldn't bring the design of the application back to the drawing board, and reconsider. 可以提供一些解决方案,所有这些问题都使您质疑是否不应该将应用程序的设计带回绘图板,然后重新考虑。 However these are some of the options: 但是,以下是一些选项:

You will have to somehow pass along the type somehow. 您将必须以某种方式传递类型。 This can be accomplished by passing the T class, an instance of T, or a pre-existing array of T. I offer the second solution, which would make the initialization look as follows: 这可以通过传递T类,T的实例或T的预先存在的数组来实现。我提供了第二种解决方案,它将使初始化如下所示:

  public DirectedGraph(Class<? super T> class) {
      this.vertices = (T[]) Array.newInstance(clazz, DEFAULT_CAPACITY);
      this.edges = new double[DEFAULT_CAPACITY][DEFAULT_CAPACITY];
  }

Then for MyMap, as the default constructor in the parent is gone in DirectedGraph (we added a parameter), you will have to add one in MyMap instead: 然后对于MyMap,由于父级中的默认构造函数在DirectedGraph消失了(我们添加了一个参数),因此您必须在MyMap添加一个:

  public MyMap() {
    super(City.class);
  }

With these code changes, I get just a step further. 通过这些代码更改,我只走了一步。 But because I have incomplete logic for the initialization, or because it has other issues a next unrelated error pops up. 但是,由于我的初始化逻辑不完整,或者由于它具有其他问题,因此会弹出下一个无关的错误。

I want to link following postings: 我想链接以下帖子:

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

相关问题 为什么我不能将一个非常规类型的 Arraylist&lt;&gt; 注册到一个 ArrayList&lt;&gt; 中? - Why cant i register a non-regular type Arraylist<> into an ArrayList<>? 具有泛型arraylist返回类型和参数的el函数 - el function with generic arraylist return type and with parameter 为什么我不能使用ArrayList <String> 作为通用ArrayList的参数 <E> 方法? - Why can't I use ArrayList<String> as a parameter for a generic ArrayList<E> method? 为什么我不能在方法中添加更多然后这个参数 - Why cant i add more then this one parameter to the method 通用数组列表方法中的通用参数 - Generic parameter in method for generic arraylist 有没有一种方法可以检查通用参数(HashMap <Integer, ArrayList<?> &gt;)是certian类型的? - Is there a way to check if a generic parameter (HashMap<Integer, ArrayList<?>>) is of a certian type? 对泛型类型使用 Class 参数(例如 ArrayList) - Use Class parameter for generic type (e.g ArrayList) 如何将通用项添加到通用ArrayList? - How do I add generic items to a generic ArrayList? 为什么我不能创建通用 class 的通用 arraylist 成员? - Why cannot I create generic arraylist member of generic class? 为什么在这里省略泛型类型参数是可以接受的? - Why is it acceptable to omit the generic type parameter here?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM