I want to know if Vector is holding <String>
or <Integer>
.
my function public void printVector(Vector <?> v){
I tried if(v instanceof <String>)
but the compiler won't allow it.
whats the issue?
I want to know if Vector is holding <String>
or <Integer>
.
my function public void printVector(Vector <?> v){
I tried if(v instanceof <String>)
but the compiler won't allow it.
whats the issue?
A code example that may be relevant:
import java.util.Iterator;
import java.util.Vector;
public class Cool {
public static void main(String[] args) {
Vector<Integer> v;
v = new Vector<>(5);
v.add(Integer.valueOf(5));
test(v);
}
private static void test(Vector<?> v) {
Iterator<?> iterator = v.iterator();
if (iterator.hasNext()) {
System.out.println(iterator.next().getClass());
}
}
}
This will print out class java.lang.Integer.
Your "test" method will have to check the type against a set of superclasses you're interested in (Employee/Customer/etc).
Also, Using vectors is generally considered bad practice in java.
Theoretically, you cannot know, because of type erasure. Basically, it means that you cannot get the generic type of the vector at runtime.
Now, in a real application, if you know that every objects are of the same type, you can get the first one and check its type with instanceof.
Note : this is not a good practice. Avoid that if you can. And as said by the others, you should consider other collections than Vector.
Note : as a rule of thumb, using instanceof
is a clue of design flaw. Also, this is a costly operation.
If there is no first element, then your array is empty so you can just drop it.
As has been pointed out, Java's type erasure will make the compile-time generic type information unavailable run-time.
A common workaround for this is to pass the Class
of the generic parameter as a method argument. This way you can then check whether the method was indeed passed a list of Customer
s or Employee
s:
public void print(List<?> list, Class<?> clazz) {
if (clazz == Employee.class) {
// ...
} else if (clazz == Customer.class) {
// ...
} else {
// ...
}
}
You could then call the method as follows:
Vector<Employee> legacy = new Vector<>();
// do stuff
print(legacy, Employee.class);
Note that resorting to instanceof
or class
checks is usually a sign of bad object oriented design and in general, you can achieve a more elegant solution through polymorphism, i.e. overriding the print()
method for different object types -- or having a single print()
method that utilizes different toString()
implementations of the domain objects.