Why is it that in Java you can't have a vector of a certain type - so that you wouldn't have to cast everything on the way out. Is this so that things can be resolved at compile time? Using STL in C++ you can have a vector of class A, which is nice. Thanks.
Please ignore post, I have no idea what I am talking about.
Well I am no c guru by any means, but it is my understanding that java is a more strongly "typed" language than c/c++. Therefore the variables that hold objects are forced to be compliant with the object type. The only way that a vector can hold ANY type of object is to have only hold "Object". In c when you have a vector of class A, you are actually cheating on what the type of that vector is. Class A may be your private class, so certainly there is no class out there that is TRUELY a Vector of Class A, the language just puts some sort of a filter on it to insure the type that it is holding is the one that you requested. This makes it less strongly typed than java. In less strongly typed languages, passing the wrong kind of argument creates problems that may not show up until runtime. If it is strongly typed, type errors are discovered during compilation, not runtime. The result is a more predictable development environment. [This message has been edited by Cindy Glass (edited May 16, 2001).]
"JavaRanch, where the deer and the Certified play" - David O'Meara
Ok. Am I able to subclass Vector to make a container that will only hold (for example) class X objects? I would not have to cast anything if that were the case. (Is this a silly question?) A Vector is great, but if I am only ever going to be using class X than why do I have to cast all the time? Thanks.
I heard that with a new release of java 1.4 the collections will be able to hold concrete objects without casting back to the object you really want to be dealing with. This will increase in performance because it will be resolved at compile time. I think with the next release we will also have templates.
Yes, the solution that you mentioned is one of the more popular work-rounds to the old "Collection returns Object" problem. ( The other is to just remember to cast your reference whenever you take it out... what you are doing currently. ) It's not a big deal to make a "wrapper" for your collection class that only accepts and returns certain types of objects...
If you need code, just ask...
Write once, run anywhere, because there's nowhere to hide! - /. A.C.