Re: Vectors and accessing elementCount - Newbie Question
I just discovered the Vector class today and am having trouble
Do you mean java.util.Vector? If so, you'll be much, much better off starting
with ArrayList as your first List implementor. Please hold off on Vector, a
very old, pre-Collection class, until you know about multi-threaded programming.
accessing the variable elementCount. First I received a protected
package error so I adjusted for this by creating another class that
This is an antipattern.
When I try to compile below, the error I'm encountering is:
"MyProg.java:9: warning: [serial] serializable class myVector has no
definition of serialVersionUID
public class myVector extends Vector"
This has to do with building a correct implementation of java.io.Serializable.
Let's defer that for a moment. It is nothing to do with access to the
protected variable, something else you should not do.
You will be much, much better off either extending (yecch) ArrayList, or
extending AbstractList, or building your own version of a List altogether.
List provides the method size() that you should use in preference to any
direct access to a member variable.
However, you should not extend List, you should include a List as a member
variable of your custom class.
Besides being way too old, Vector has the feature that all its methods are
synchronized. Usually this is overhead you do not want, because you only need
thread-local access to your List. Even if you do need to synchronize access,
you can use one of the prebuilt concurrent structures, or make a
Collections.synchronizedCollection( yourList ).
Now, about that java.io.Serializable implementation.
Read and study this link, and the related material in Joshua Bloch's book,
If you make a class implement java.io.Serializable you pretty much should
have, but the language does not require, a member variable:
ANY-ACCESS-MODIFIER static final long serialVersionUID
where "ANY-ACCESS-MODIFIER" can be any access modifier, including no access
modifier (package-private). That's what the error message told you was missing.
Implementing java.io.Serializable is a huge responsibility. It commits the
class maintainer permanently to details of an implementation, and to an
additional exposed face to the class that provides a back door to the internals.