TCLUG Development Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [TCLUG-DEVEL:267] Vector.toArray()




> Am I missing something here?
> 
> I want to convert a Vector of Strings to an array of Strings.
> 
> Vector foo = new Vector()
> foo.add("1");
> foo.add("2");
> foo.add("3");
> foo.add("4");
> 
> String[] blah = new String[4];
> blah = (String[])foo.toArray();
> 
> Should this work?

I just did some experiments and it looks like you need to either

    (1) pass 'blah' as an argument to toArray, as in

	   blah = (String[])foo.toArray(blah);

 or (2) declare blah to be Object[] and then cast its members to type
        String when you use them, as in

	   Object[] blah = foo.toArray();
	   String s1 = (String)blah[1];
	   String s2 = (String)blah[2];
	   ... etc ...

Notice that there are actually two versions of toArray:

    (1) public Object[] toArray(Object[] a)
and (2) public Object[] toArray()

I guess the second one creates an Array that really just holds things
of class Object, where as the first one creates an array whose base
type is the actual type that you pass in as the arg 'a'.

--Mark

Mark Phillips @ Geometry Technologies, Inc.
550 Gilbert Building, 413 Wacouta St., St. Paul, MN 55101
Phone: 651-223-2884  Fax: 651-292-0014
mbp@geomtech.com       http://www.geomtech.com