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
  • 398,947
  • 96
  • 818
  • 769
user559142
  • 12,279
  • 49
  • 116
  • 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
  • 292,901
  • 67
  • 465
  • 588
3

I think what you are looking for are generics:

public Vector<String> objVector = new Vector<String>(50);
sfussenegger
  • 35,575
  • 15
  • 95
  • 119
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,276
  • 7
  • 34
  • 54
TheArchon
  • 313
  • 5
  • 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,762
  • 28
  • 132
  • 190
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,