Amazing: Vector can have elements of different types!!!

S

Shawn

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;
}
}
 
M

Matt Humphrey

Shawn said:
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)?


Yes, this is done all the time, is very useful and can be a terrible source
of confusion (if not outright bad design) if not done properly.
(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)

Yes, use instanceOf or getClass() on the object returned, realizing that
doing so may signal something wrong with your design. You can see the
confusion when you say "I forgot 1st element is a ..."
(3)Is this actually a drawback that Generics from Java 5.0 wants to cover
up?

It's not so much that the ability to store objects of different types is a
fault as it is a necessary fundamental building block that can be misused.
Really, it's only storing one kind of object--subclasses of Object, but that
declaration covers a lot of sins. Good designs most commonly simply refine
the declaration so that the collection stores subclasses of some other
class, such as Person, IMyOtherComponent, etc, so that there's no
"forgetting" what the collection contained and casting the retrieval to the
right kind of variable as a simple kind of check. Generics provide a syntax
for that declaration, compiler support for checking it and some nice
features like autoboxing to reduce unnecessary casting code.

You could say that part of the problem is that collections of any type (even
with generics) do not have runtime constraints on the types of objects they
can hold. But I believe that runtime type checking usually comes too late
to be useful--it always signals a program error. The value of generics is
that they validate code at compile time in order to prevent these messes at
runtime.

Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
S

Shawn

Matt said:
Yes, this is done all the time, is very useful and can be a terrible source
of confusion (if not outright bad design) if not done properly.

Thank you very much. Patricia previously said that she usually doesn't
put different types into one collection. Could you give me some examples
that you would do so?
 
P

Patricia Shanahan

Shawn said:
Thank you very much. Patricia previously said that she usually doesn't
put different types into one collection. Could you give me some examples
that you would do so?

I didn't say exactly that. I said "I don't usually mix classes whose
only common superclass is Object. More often, all the elements implement
or extend a specific interface or class other than Object."

Two objects can be of different types, but both implement a common
interface or extend a common superclass other than Object.

For example, the class javax.sql.BaseRowSet uses a Vector containing
references to RowSetListener. RowSetListener is an interface, so any
objects referenced by the Vector will be of some class implementing the
interface. There is no reason to expect them to all be of the same class.

Patricia
 
C

Chris Uppal

Shawn said:
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)?

Yes, very common. There are good reasons to do it (which is common) and there
are bad reasons to do it (which I hope and trust is rare). The good reasons
are when all the objects have /something/ in common -- for instance they could
all implement some specific interface, or they could share a common
(non-trivial) base class. In that case the code using the collection doesn't
care what kinds of objects they are /except/ that they have the common
property. You could say that from that code's point-of-view the collection
/isn't/ heterogeneous -- they are all the exactly same kind of thing in the
only sense it cares about.

So you end up with code like (for example):

Interface fireable { void fire(); }

List = // ... some list

for (Iterator it = list.iterator(); it.hasNext(); )
{
Fireable f = (Fireable)it.next();
f.fire();
}

Generics, in 1.5, are an attempt to formalise this sort of pattern.

However there are also bad reasons for creating heterogeneous lists. A
reasonable (but certainly not 100% reliable) rule-of--thumb is that you are
going wrong if you ever need an answer to:
(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)

-- chris
 
S

Shawn

I understand dynamic binding concept, which each object will do its own
operations on the fly based on who it is. All these objects have a
common superclass, or the same type.

But I never thought String, arrays, Integer, Double, Person objects
could be put in one collection.
 
S

Shawn

I understand dynamic binding concept, which each object will do its own
operations on the fly based on who it is. All these objects have a
common superclass, or the same type.

But I never thought String, arrays, Integer, Double, Person objects
could be put in one collection. I know they are subclasses of Class
Object. So they can be viewed as the same type. I just feel amazed about
that.
 
P

Patricia Shanahan

Shawn said:
I understand dynamic binding concept, which each object will do its own
operations on the fly based on who it is. All these objects have a
common superclass, or the same type.

But I never thought String, arrays, Integer, Double, Person objects
could be put in one collection.

One of the most fundamental rules in Java is that EVERY class extends
Object, directly or indirectly.

Patricia
 
M

Mark Jeffcoat

Shawn said:
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).

Other people have hinted at this, but I'll state it directly:

Pre-generics, collection classes accepted one and only one type:
Object. From the Vector's point of view, all the data that you
are putting into it is perfectly homogenous.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top