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

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

问题描述

我知道如何对如何检查arraylist中每个对象的类型进行硬编码,但是有没有其他方法可以一口气检查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中都是人对象时,我怎么知道该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>,则如果编写的代码可以将非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天全站免登陆