Re: Amazing: Vector can have elements of different types!!!
- From: Shawn <shaw@xxxxxxxxxx>
- Date: Fri, 15 Sep 2006 10:55:36 -0400
Matt Humphrey wrote:
I have a couple questions:
(1)Is that common that people utilize this feature (putting different
types of data in one place)?
Yes, this is done all the time, is very useful and can be a terrible source of confusion (if not outright bad design) if not done properly.
Thank you very much. Patricia previously said that she usually doesn't put different types into one collection. Could you give me some examples that you would do so?
.(2)Is there a way to find out what type of each element belongs to? (say
I forgot 1st element is Person, 2nd element is String, etc)
Yes, use instanceOf or getClass() on the object returned, realizing that doing so may signal something wrong with your design. You can see the confusion when you say "I forgot 1st element is a ..."
(3)Is this actually a drawback that Generics from Java 5.0 wants to cover up?
It's not so much that the ability to store objects of different types is a fault as it is a necessary fundamental building block that can be misused. Really, it's only storing one kind of object--subclasses of Object, but that declaration covers a lot of sins. Good designs most commonly simply refine the declaration so that the collection stores subclasses of some other class, such as Person, IMyOtherComponent, etc, so that there's no "forgetting" what the collection contained and casting the retrieval to the right kind of variable as a simple kind of check. Generics provide a syntax for that declaration, compiler support for checking it and some nice features like autoboxing to reduce unnecessary casting code.
You could say that part of the problem is that collections of any type (even with generics) do not have runtime constraints on the types of objects they can hold. But I believe that runtime type checking usually comes too late to be useful--it always signals a program error. The value of generics is that they validate code at compile time in order to prevent these messes at runtime.
Matt Humphrey matth@xxxxxxxxxxxxxx http://www.iviz.com/
- Follow-Ups:
- Re: Amazing: Vector can have elements of different types!!!
- From: Patricia Shanahan
- Re: Amazing: Vector can have elements of different types!!!
- References:
- Amazing: Vector can have elements of different types!!!
- From: Shawn
- Re: Amazing: Vector can have elements of different types!!!
- From: Matt Humphrey
- Amazing: Vector can have elements of different types!!!
- Prev by Date: Re: hashcode
- Next by Date: Re: servlet request handling - escaped characters in request
- Previous by thread: Re: Amazing: Vector can have elements of different types!!!
- Next by thread: Re: Amazing: Vector can have elements of different types!!!
- Index(es):
Relevant Pages
|