Java中将Object []数组转换为泛型类型数组时发生ClassCastException [英] ClassCastException when casting Object[] array to generic type array in Java

查看:138
本文介绍了Java中将Object []数组转换为泛型类型数组时发生ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,在这段代码中,我想不是在Main中正确创建Bag?

Hi I'm very new to Java and in this code, I think I'm not creating the Bag correctly in the Main? Please help thanks!

线程 main中的异常java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.Comparable;
位于中间包(Bag.java:12)
位于中间中间包(Bag.java:91)

        public class Bag<T extends Comparable<T>> implements Iterable<T> {
      private int MAX_ITEMS = 10; // initial array size
      private int size;
      private T[] data;

      public Bag( ) {
        data = (T []) new Object[MAX_ITEMS];
        size = 0;
      }

      public void add(T newItem) {
        // check if it's full, then extend (array resizing)
        if (size == data.length) {
          T[ ] temp = (T [ ] ) new Object[data.length*2];
          for (int i = 0; i < size; ++i)
            temp[i] = data[i];
          // reassign data to point to temp
          data = temp;
        }
        // then do the assignment
        data[size++] = newItem; // assign newItem in the next-available slot
      }

public Iterator<T> iterator() {
    return new BagIterator();
  }

 /***************************
  * nested class BagIterator
  ***************************/
   class BagIterator implements Iterator<T> {
    // instance member
    private int index;

    // (0) constructor
    public BagIterator() {
      index = 0;
    }
    // (1)
    public boolean hasNext() {
      return (index < size); // size in the outer Bag<E>
    }
    // (2)
    public T next() {
      /*
      T temp = data[index]; // save the element value
      index++; // increment index
      return temp;
      */
      return data[index++];
    }
      public static void main(String[ ] args) {
          Bag<String> bag1=new Bag<String>();

          bag1.add("good");
          bag1.add("fortune");
          bag1.add("billionarie");
          for (String x: bag1)
              System.out.println(x);

      }


推荐答案

是的,您正在创建 Object [] ,然后尝试将其转换为 T [] ,编译器将其转换为由于您对T的限制,强制转换为 Comparable [] (使用原始的 Comparable 类型)。

Yes, you're creating an Object[] and then trying to cast it to T[], which the compiler is converting to a cast to Comparable[] (using the raw Comparable type) due to your constraint on T.

基本上,数组和泛型不能很好地协同工作。

Arrays and generics don't work terribly nicely together, basically.

制作<$可能会更简单c $ c> data 字段只是一个 Object [] 字段,并在需要时强制转换单个值。

It would probably be simpler to make your data field just an Object[] and cast individual values where necessary.

这篇关于Java中将Object []数组转换为泛型类型数组时发生ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆