返回从泛型类的数组。我如何在main方法的阵列打印数据? [英] Returning an array from a generic class. How do I print the data from the array in main method?

查看:109
本文介绍了返回从泛型类的数组。我如何在main方法的阵列打印数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法理解我应该如何使用从中的主要方法returnItems()返回的数组。我有点被泛型类型吓倒。我失去了我的信心,如果我要继续我的梦想成为一名Java开发人员。当我读到由专业人员一些code似乎他们都喜欢使用泛型的,但我觉得它很吓人。我想AP preciate它,如果我能得到的仿制药,我可以很容易地理解一个很好的参考。

 公共类通用< T> {
    私人诠释POS;
    私人最终诠释大小;
    私人T [] arrayOfItems;
    公共通用(INT大小)
    {
        this.size =大小;
        POS = 0;
        arrayOfItems =(T [])新对象【尺寸】;
    }
    公共无效的addItem(T项)
    {
        arrayOfItems [POS] =项目;
        POS ++;
    }
    公共无效displayItems()
    {
        的for(int i = 0; I< POS;我++){
        的System.out.println(arrayOfItems [I]);
        }
    }
    大众T [] returnItems()
    {
        返回arrayOfItems;
    }
}
公共类GenericTesting {
    公共静态无效的主要(字串[] args){
        通用<串GT;动物=新的通用<串GT;(5);
        通用<整数GT;数=新的通用<整数GT;(5);
        animals.addItem(犬);
        animals.addItem(猫);
        animals.addItem(鸟);
        animals.addItem(鼠标);
        animals.addItem(大象);
        animals.displayItems();        numbers.addItem(1);
        numbers.addItem(2);
        numbers.addItem(3);
        numbers.displayItems();        的for(int i = 0; I< animals.returnItems()长;我++)
        {
            的System.out.println(animals.returnItems [I]);
        }
    }}


解决方案

returnItems()是返回一个数组,而不是数组本身的方法,这样你就可以 ŧ试图在它引用索引像你想在这里做的:

 的System.out.println(animals.returnItems [I]);

您需要做的是从参考方法返回数组的索引像这样:

 的System.out.println(animals.returnItems()[我]);

修改

你还要在你存储数据并返回它的方式有问题。在构造函数创建 arrayOfItems 作为数组对象

  arrayOfItems =(T [])新对象【尺寸】;

...但你尝试将它在 returnItems()返回为 T 的数组:

 公共T [] returnItems()
{
    返回arrayOfItems;
}

当您尝试运行code,你会得到一个异常:

  java.lang.ClassCastException:[Ljava.lang.Object;不能转换为[Ljava.lang.String;

这是由于一种叫做类型擦除。基本上,Java编译器会与普通班(对象在这种情况下),以取代所有的泛型类型,并插入强制转换为preserve类型安全。

所以,这条线从的main()方法:

 的for(int i = 0; I< animals.returnItems()长;我++)

将要看到动物通用<弦乐> ,且变成这样:

 的for(int i = 0; I<((字符串[])animals.returnItems())长;我++)

但是,你正在返回被作为新的对象[] 不会 新的String创建数组[ ] ,并且你不能垂头丧气,除非对象实际上是子类型,因此例外。

要消除 ClassCastException异常,你可以改变 returnItems()来申报其实际的返回类型是这样的:

 公共对象[] returnItems()
    {
        返回arrayOfItems;
    }

这将会使编译器试图插入阵列的非法投,但随后你需要每个元素转换为手动合适的类型,这违背首先使用泛型的目的。

如上的评论所指出的JBNizet,数组和仿制药不顺利在一起,所以你会更好使用的ArrayList< T> 而不是 T [] 来存储你的数据。

I can't seem to understand how I should be using the returned array from returnItems() in the main method. I am a bit intimidated by generic types. I am losing my confidence if I should continue on my dream becoming a java developer. When I read some code by professionals it seems that they are fond of using generics, but I find it very intimidating. I would appreciate it if I could get a good reference for generics that I can easily understand.

public class Generic<T> {
    private int pos;
    private final int size;
    private T[] arrayOfItems;
    public Generic(int size)
    {
        this.size = size;
        pos = 0;
        arrayOfItems = (T[]) new Object[size];
    }
    public void addItem(T item)
    {
        arrayOfItems[pos] = item;
        pos++;
    }
    public void displayItems()
    {
        for(int i = 0;i<pos;i++){
        System.out.println(arrayOfItems[i]);
        }
    }
    public T[] returnItems()
    { 
        return arrayOfItems;
    }
}


public class GenericTesting {
    public static void main(String[] args) {
        Generic<String> animals = new Generic<String>(5);
        Generic<Integer> numbers = new Generic<Integer>(5);
        animals.addItem("Dog");
        animals.addItem("Cat");
        animals.addItem("Bird");
        animals.addItem("Mouse");
        animals.addItem("Elephant");
        animals.displayItems();

        numbers.addItem(1);
        numbers.addItem(2);
        numbers.addItem(3);
        numbers.displayItems();

        for(int i=0; i < animals.returnItems().length;i++)
        {
            System.out.println(animals.returnItems[i]);
        }
    }

}

解决方案

returnItems() is a method which returns an array, not an array itself, so you can't try to reference an index on it like you are trying to do here:

        System.out.println(animals.returnItems[i]);

What you need to do is reference the index on the array returned from the method like so:

        System.out.println(animals.returnItems()[i]);

Edit

You've also got a problem in the way that you store your data and return it. In your constructor you create arrayOfItems as an array of Object:

        arrayOfItems = (T[]) new Object[size];

...but you try to return it as an array of T in returnItems():

public T[] returnItems()
{ 
    return arrayOfItems;
}

When you try to run your code, you're going to get an exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

This is due to something called type erasure. Basically the Java compiler is going to replace all of your generic types with ordinary classes (Object in this case), and inserts casts to preserve type safety.

So this line from your main() method:

    for(int i=0; i < animals.returnItems().length;i++)

is going to see that animals is a Generic<String>, and turn into this:

    for(int i=0; i < ((String[])animals.returnItems()).length;i++)

But the array that you are returning was created as a new Object[], not a new String[], and you can't downcast unless the object actually is of the child type, hence the exception.

To eliminate the ClassCastException, you could change returnItems() to declare its actual return type like this:

    public Object[] returnItems()
    { 
        return arrayOfItems;
    }

This would keep the compiler from trying to insert an illegal cast of the array, but then you'd need to cast each element to the appropriate type manually, which defeats the purpose of using generics in the first place.

As pointed out by JBNizet in the comments above, arrays and generics "don't go well together", so you'd be better off using an ArrayList<T> instead of a T[] to store your data.

这篇关于返回从泛型类的数组。我如何在main方法的阵列打印数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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