查找保存在ArrayList< Object>中的特定类型。 (即Object = String等) [英] Finding the specific type held in an ArrayList<Object> (ie. Object = String, etc.)

查看:108
本文介绍了查找保存在ArrayList< Object>中的特定类型。 (即Object = String等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个ArrayList,我已经转换为对象的ArrayList。我知道所有在ArrayList中的对象都是相同的类型,但不是类型。

Say I have an ArrayList that I have cast to an ArrayList of objects. I know that all the objects that were in the ArrayList I cast were of the same type, but not what the type was.

现在,如果ArrayList不为空,我可以采取其中的一个对象,并使用instanceof运算符来了解实际类型是什么。但是ArrayList为空的情况是什么?我如何确定什么类型对象实际上是什么?可能吗?

Now, if the ArrayList is not empty, I could take one of the objects in it and use the instanceof operator to learn what the actual type is. But what of the case where the ArrayList is empty? How do I determine what type Object actually is then? Is it possible?

编辑:回想起来,我想这不是严格的什么类型的一个空的ArrayList持有。我可以丢弃旧的和构造一个新的空ArrayList的正确类型我在寻找在第一个地方。

In retrospect, I suppose it doesn't strictly matter what type an empty ArrayList holds. I can discard the old one and construct a new empty ArrayList of the proper type I was looking for in the first place.

这有点凌乱,所以如果任何人有替代建议如何允许各种各样的潜在类型,可能不共享相关的公共超类(Ex。Integer和ArrayList ),我乐意接受建议。事情是,我有一个类,将包含其他类专门设计为可互换使用。包含的类可以对类型做出假设,因为它们是定义它的类型。周围的类不能做这样的假设,但必须确认它指定的类型与已经被插入其中的包含的类相同。

It's a bit messy, so if anyone has alternate suggestions for how to allow a large variety of potential types which may not share a relevant common superclass (Ex. Integer and ArrayList), I'm open to suggestions. The thing is, I have a class that will contain other classes specifically designed to be interchangably used within it. The contained classes can make assumptions as to the type, as they're the ones defining it. The surrounding class cannot make such assumptions, but must confirm that it is specifying the same type as the contained classes that have been slotted into it.

因此,我的问题,因为包含的类是通用的(通用指定它正在处理什么类型的类型),但它必须确保被传递的包含的类返回并对指定的类型进行操作(它们被设计为单独创建,因此它们匹配的事实必须在插入时而不是在创建时确认)。

Thus my question, as the containing class is generic (the generic specifying what sort of type it is handling), but it must ensure the contained classes it was passed are returning and operating on the type that was specified to it (they are designed to be created separately and as such the fact that they match must be confirmed when they are slotted in, not at the time of their creation).

推荐答案

不, type erasure 确保这一点。

这篇关于查找保存在ArrayList< Object>中的特定类型。 (即Object = String等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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