Is the following valid in Java:
public Vector <Object> objVector = new Vector <Object>(50);
I know by default the values are stored as objects, but I would like to know how to restrain the contents by type...
Thanks
Is the following valid in Java:
public Vector <Object> objVector = new Vector <Object>(50);
I know by default the values are stored as objects, but I would like to know how to restrain the contents by type...
Thanks
This is ancient code.
Use Generics, and use modern collection types (don't use Vector), then you get compile-time checks automatically:
List<String> list = new ArrayList<String>()
list.add(new Foo()); // compile-time failure
list.add("SomeString"); // ok
I think what you are looking for are generics:
public Vector<String> objVector = new Vector<String>(50);
By 'valid', it's syntax is fine:
public Vector <Object> objVector = new Vector <Object>(50);
In the NetBeans Platform 8:0:2 that I'm using, it will show a Obsolete Collection, it is much better to use an ArrayList
, although a Vector
has a advantage, it can store pretty much anything.
The declaration:
Vector v = new Vector();
Which constructs a empty Vector,this type of Vector can 'add' ints, booleans, an ArrayList's and other primitive data types and references.
I would like to know how to restrain the contents by type...
Simply specify the type while instantiating the vector:
public Vector <concreteType> objVector = new Vector <concreteType>(50);
Using generics you can specify a hierarchy based type restriction:
class yourClass<TYPE extends SomeType>{
public yourClass(){
public Vector <TYPE> objVector = new Vector <TYPE>(50);
}
}
In the last example TYPE can be any type that extends SomeType (SomeType included). You can use the keyword implements, to restrict TYPE's type to interfaces instead of classes.
you can specify the type in the angular bracs: vector vv = new vector(); instead of string you can specify any data type. this means you restrict the vector to use only the specified type of data can be accepted in vector. Thankyou,