java:如何从整体上检查 ArrayList 的类型 [英] java: how to check the type of an ArrayList as a whole

查看:54
本文介绍了java:如何从整体上检查 ArrayList 的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何对如何检查数组列表中每个对象的类型的算法进行硬编码,但是有没有其他方法可以一次性检查该 ArrayList<> 的类型,我的意思是我的应用程序只有三个数组列表的类型.假设我有一个返回 ArrayList 的函数,它的定义是在变量 o(当然它是对象的数组列表)中我将添加一个 person 对象,

i know how to hard code an algorithm on how to check the types of each object in an arraylist, but is there any other way in checking the type of that ArrayList<> in one go, i mean my application has only three types of arraylist. Say i have a function that returns an ArrayList, and its definiton is that in a variable o (its an arraylist of object ofcourse) i'll add a person object,

o.add(person);

并在对象数组列表中添加了所有人员数据,并且在调用此函数时说我的函数名称是 getData(),

and having added all person data on an arraylist of objects and when a call this function say the name of my function is getData(),

ArrayList <Object> obj = getData();

所以我知道在我通过调用 getData() 返回的那个 ArrayList 中,它是 all person 对象,我怎么知道那个 ArrayList 的类型?.

so i know that in that ArrayList that i returned from calling getData() that it is all person object, how do i know the type of that ArrayList?.

只是希望该功能在某种意义上更通用,但这适用于我的应用程序,在我的应用程序中通用.

Just wanted that function to be more generic in sense, this is for my application though, geniric troughout my application.

有没有其他方法可以做到这一点,我可以想到一个算法,但有没有捷径或简单的方法来做到这一点?..

Is there any other way of doing this, i can think of an algorithm but is there any short cut or easy way of doing this?..

推荐答案

ArrayList 没有类型"这样的东西.

There is no such thing as 'the type' of an ArrayList.

ArrayList 类存储了一个 Object 引用列表.它不知道也不关心它们是否都是某种类型.

The class ArrayList stores a list of Object references. It doesn't know and doesn't care if they are all of some type.

Java 泛型系统添加了编译时检查以帮助您跟踪类型.因此,如果您声明 ArrayList,并且您编写的代码可能会插入非 Person 到您的列表中,则会出现编译错误.

The Java generic system adds compile-time checking to help you keep track of types. So, if you declare ArrayList<Person>, you will get compile errors if you write code that could insert a non-Person into your list.

在运行时,唯一的方法是判断 ArrayList 中的内容,以遍历所有包含的项目并使用 instanceof 进行检查.

At runtime, the only way to tell what is in an ArrayList to iterate over all the contained items and check them with instanceof.

这篇关于java:如何从整体上检查 ArrayList 的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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