How do I make a collection where all the elements within it are a specific data type?

John Zukowski

Until there is support for generic types in Java, you'll need to create a collection that overrides the methods that add elements into the collection. In these methods, you would check for the appropriate data type, which would need to be passed into the constructor, or set in some other manner, depending upon how generic you'd like to be. If the wrong type came in, then you would need to throw an exception.

Since the add methods all accept any Object subclass, this can only be done with subclassing.

To get elements out, you would either have to introduce new methods to get the specific type back or just cast the Object returned from the existing methods to retrieve elements.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact