简体   繁体   English

如何在Java中的列表中保留两个不同的对象?

[英]How to keep two different objects in List in java?

I want to create list and I have two different objects like employee and user .If I need employee and user object both into the list. 我想创建列表,并且有两个不同的对象,例如employee和user。如果需要在列表中同时包含employee和user对象。 Where will write the employee object and where will write user object . 在哪里写员工对象,在哪里写用户对象。 How to make different objects list view. 如何使不同的对象列表视图。

I am certain that there is a better way to achieve what you want. 我敢肯定,有一种更好的方法来实现您想要的。 Try writing down what you need to do, and think of ways to store the different objects. 尝试写下您需要做的事情,并思考存储不同对象的方法。

However, to directly answer your question you can make a generic list of Object like so: 但是,要直接回答您的问题,您可以制作一个通用的Object列表,如下所示:

List<Object> myList = new ArrayList<Object>();
myList.add(employee);
myList.add(user);

Beware that this will store any type of object, so whenever you take things back out of the list you will need to check what sort of object it is and then cast it like so: 请注意,这将存储任何类型的对象,因此,每当您从列表中取出东西时,都需要检查它是什么类型的对象,然后像这样进行转换:

if (myList.get(x) instanceof Employee)
{
    //Cast to an Employee and then do whatever you want
    Employee fromList = (Employee)myList.get(x);
}
else if (myList.get(x) instanceof User)
{
    //Cast to an User and then do whatever you want
    User fromList = (User)myList.get(x);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM