Amazing: Vector can have elements of different types!!!
Hi,
I just realized/found that in Java, Vector can have elements with
different types. I guess other collections are the same. See my code
below. I don't know Generics from Java 5.0. But I am really amazed that
heterogenous types of data can be put in the same place(Vector).
I have a couple questions:
(1)Is that common that people utilize this feature (putting different
types of data in one place)?
(2)Is there a way to find out what type of each element belongs to? (say
I forgot 1st element is Person, 2nd element is String, etc)
(3)Is this actually a drawback that Generics from Java 5.0 wants to
cover up?
Thank you very much.
=============TestDemo.java============
import java.util.*;
public class TestDemo {
public static void main(String[] args)
{
Vector myVec = new Vector();
Person aPerson = new Person("Tom");
String aString = "Hello World";
int[] intArray = {3, 5, 9};
myVec.addElement(aPerson);
myVec.addElement(aString);
myVec.addElement(intArray);
Person newPerson = (Person)myVec.elementAt(0);
System.out.println("Here is the person:" + newPerson.getName());
//print Tom
String newString = (String)myVec.elementAt(1);
System.out.println("Here is the string:" + newString); //print Hello
World
int[] newArray = (int[])myVec.elementAt(2);
System.out.println("Here is the array element: " + newArray[1]);
//print 5
}
}
==============Person.java================
public class Person {
private String sName;
public Person()
{
//empty
}
public Person(String s)
{
this.sName = s;
}
public String getName()
{
return sName;
}
}