Is there a way to create a homogenous collection in Java? How do I make a collection where all the elements within it are a specific data type?

Joseph Shelby

You can wait for Generics to be added to Java or...

You'd have to build one yourself. Basically, you're creating a class that is a Proxy (Gang Of Four design pattern) around the actual Collection.

This works similarly to the way the (hidden) Synchronized versions in Collections work. They contain a reference to the original collection object that does the "real" work, but restrict access to it by synchronizing all the access methods.

What you'd be doing in this case is restricting access by keeping a reference to the Class object of the class you want to restrict your collection to contain, and throw IllegalArgumentExceptions whenever there's an attempt to add an object not of that class.

There's no way to enforce compile-time type safety in this manner. The API using "Object" references can't be changed in Collection.

You can also wrap a collection by a Proxy that provides the alternative API that has type-safe method signatures. This is what's done by the StringTokenizer API (which implements Enumeration, and wraps Enumeration with String versions of the same methods).

Otherwise, create your own class with its own signatures, and keep the Collection strictly private. This is best done if you are designing a class for others to use.

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

 

 

 

 

 


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

 

 

About | Sitemap | Contact