3

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

skaffman
  • 390,936
  • 96
  • 800
  • 764
user559142
  • 11,719
  • 47
  • 114
  • 179

5 Answers5

9

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
Community
  • 1
  • 1
Sean Patrick Floyd
  • 284,665
  • 62
  • 456
  • 576
3

I think what you are looking for are generics:

public Vector<String> objVector = new Vector<String>(50);
sfussenegger
  • 34,561
  • 14
  • 93
  • 118
1

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.

Prudhvi
  • 2,162
  • 7
  • 35
  • 51
TheArchon
  • 303
  • 3
  • 15
1
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.

Heisenbug
  • 38,154
  • 28
  • 129
  • 182
0

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,