创建不同对象的实例列表 [英] Creating instance list of different objects

查看:117
本文介绍了创建不同对象的实例列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图创建一个包含不同类实例的arraylist.如何在不定义类类型的情况下创建列表? (<Employee>)

I'm tring to create an arraylist of different class instances. How can I create a list without defining a class type? (<Employee>)

List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee());
Employee employee = employees.get(0);

推荐答案

您可以创建对象列表,例如List<Object> list = new ArrayList<Object>().由于所有类的实现都从java.lang.Object类隐式或显式扩展,因此该列表可以容纳任何对象,包括EmployeeIntegerString等的实例.

You could create a list of Object like List<Object> list = new ArrayList<Object>(). As all classes implementation extends implicit or explicit from java.lang.Object class, this list can hold any object, including instances of Employee, Integer, String etc.

从此列表中检索元素时,将检索Object而不是Employee,这意味着在这种情况下,您需要执行以下显式强制转换:

When you retrieve an element from this list, you will be retrieving an Object and no longer an Employee, meaning you need to perform a explicit cast in this case as follows:

List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());

Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast

这篇关于创建不同对象的实例列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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