| Author |
how to allow list for only two types of objects ?
|
hitesh patil
Greenhorn
Joined: Sep 10, 2012
Posts: 1
|
|
|
how to allow list for only two types of objects ?
|
 |
ravi suthar
Greenhorn
Joined: Apr 22, 2012
Posts: 17
|
|
welcome to java runch hitesh patil..!
by default you can add any object to list.
but if you want only specific type you can use of generics.
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
hitesh patil wrote:how to allow list for only two types of objects ?
Are the two types related?
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
Unless they are related, that is rather contrary to the philosophy of collections, viz, that your collections contain things from a particular category.
|
 |
Ivan Jozsef Balazs
Ranch Hand
Joined: May 22, 2012
Posts: 380
|
|
As a work-around, you could fabricate a "synthetic" type to contain two references: either one to the first type, or one to the second type, and then declare a list for this type.
This type had two constructors: one for each given type.
Not forcibly a very nice or pleasing solution but feasible.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
You can even make the object contain one type only by careful selection of the constructors
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
Campbell Ritchie wrote:Unless they are related, that is rather contrary to the philosophy of collections, viz, that your collections contain things from a particular category.
Yeah. I was thinking more along the lines of defining an interface that both of them implement.
Winston
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
I thought you meant something like that, Winston, or a common superclass.
|
 |
 |
|
|
subject: how to allow list for only two types of objects ?
|
|
|