aspose file tools
The moose likes Beginning Java and the fly likes how to allow list for only two types of objects ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "how to allow list for only two types of objects ? " Watch "how to allow list for only two types of objects ? " New topic
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
    
    7

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
    
    4
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
    
    4
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
    
    7

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
    
    4
I thought you meant something like that, Winston, or a common superclass.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: how to allow list for only two types of objects ?
 
Similar Threads
Why is not working
sets
Mock Question Equal & Hashcode
Generics <?>
ArrayList sorting using Ccomparator