Help coderanch get a
new server
by contributing to the fundraiser
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Using a Vector within a Vector

Greenhorn
Posts: 8
• Number of slices to send:
Optional 'thank-you' note:
Is it possible to use a Vector nested inside of another Vector? I would use Arrays to accomplish this but I do not know the size of either Array in advance. I tried to use a Vector within a Vector and it initially appeared to work, but I cannot determine a way to access the individual elements of the inner Vector. Whenever I use outerVector.elementsAt(i) on the outer Vector it outputs[elem1,elem2,elem3,elem4] but I cannot find a way to actually get to and manipulate each discrete element in the inner vector. I'm sure there's a better way. Any ideas?
Code snippet:
Vector outerVector = new Vector();
...
Vector innerVector = new Vector();
...
for (int i = 0; i < innerVector.size(); i++) {
System.out.println(outerVector.elementsAt(i));
}
Output:
[elem1,elem2,elem3,elem4]

Ranch Hand
Posts: 388
• Number of slices to send:
Optional 'thank-you' note:
hi,
Vector.elementAt(i) returns an Object. Since you know the Object returned from the outerVector is also a Vector, you can just cast it to a Vector.
This is to make the Structure of Vector usable for all types in java since everithing is of type Object (the primitive datatypes like int, long, double... are not)
// retrieve a Vector "stored" in a Vector
Vector aVector = (Vector)outerVector.elementAt(i);
// now aVector is a Object of type Vector. ATTENTION: if // elementAt(i) is not a Vector a ClassCastException occurs
to check the type:
Object obj = outerVector.elementAt(i);
if (obj instanceof Vector) {
Vector aVector = outerVector.elementAt(i);
} else {
// do something other here
}

k

High Plains Drifter
Posts: 7289
• Number of slices to send:
Optional 'thank-you' note:
Vectors store their elements as Objects, so when you put one Vector inside another, it loses it's "Vectorness." To restore that, you'll need to cast to Vector before relying on that interface of operations for further processing.
The output you're seeing below is the toString() representation of your inner Vector, which seems fine to me.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide

 I can't renounce my name. It's on all my stationery! And hinted in this tiny ad: We need your help - Coderanch server fundraiser https://coderanch.com/t/782867/Coderanch-server-fundraiser