Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2006

Tip: Looking for answers? Try searching our database.

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

Thread view: 
Shawn - 15 Sep 2006 14:27 GMT
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;
    }
}
Matt Humphrey - 15 Sep 2006 15:14 GMT
> Hi,
>
[quoted text clipped - 6 lines]
> (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 matth@ivizNOSPAM.com http://www.iviz.com/
Shawn - 15 Sep 2006 15:55 GMT
>> 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.

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?

>> (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)
[quoted text clipped - 25 lines]
>
> Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/ 
Patricia Shanahan - 15 Sep 2006 16:34 GMT
>>> I have a couple questions:
>>> (1)Is that common that people utilize this feature (putting different
[quoted text clipped - 6 lines]
> 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
Chris Uppal - 15 Sep 2006 17:21 GMT
> I just realized/found that in Java, Vector can have elements with
> different types. I guess other collections are the same. See my code
[quoted text clipped - 4 lines]
> (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
Shawn - 15 Sep 2006 17:34 GMT
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.
Patricia Shanahan - 15 Sep 2006 17:37 GMT
> 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
Shawn - 15 Sep 2006 17:35 GMT
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.
Mark Jeffcoat - 15 Sep 2006 19:08 GMT
> 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.

Signature

Mark Jeffcoat
Austin, TX



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.