0

I have to get the first element of each vector and add into another vector and continue till mainVector ends

mainVector -- > [[1,Allen,2000,10],[2,Joe,3000,20],[3,King,4000,40]] [Vector(Vectors)]

output should be -- > [[1,2,3],[Allen,Joe,King],[2000,3000,4000],[10,20,40]] [Vector(Vectors)]

int i=0;
Vector outputVector = new Vector();
for(int p = 0; p < mainVector.size(); p++)        
{
       Vector second = new Vector();
       for(int h = 0; h < mainVector.size(); h++) 
       {
          eachVector = mainVector.get(h);
          String eachElement = eachVector.get(i);
          second.add(eachElement);
       }
       outputVector.add(second);
    i++;       
}
JimHawkins
  • 4,843
  • 8
  • 35
  • 55
Srinivas
  • 147
  • 1
  • 14

2 Answers2

0

Try this.

int i = 0;
Vector outputVector = new Vector();
for (int p = 0; p < ((Vector)mainVector.get(0)).size(); p++) {
    Vector second = new Vector();
    for (int h = 0; h < mainVector.size(); h++) {
        Vector eachVector = (Vector)mainVector.get(h);
        Object eachElement = eachVector.get(i);
        second.add(eachElement);
    }
    outputVector.add(second);
    i++;
}
0

You don't need 3 index variables, as you have a 2 dimensional data structure:

Vector outputVector = new Vector();
for (int i = 0; i < mainVector.size(); i++) {
    outputVector.add(new Vector());
    for (int j = 0; j < mainVector.get(0).size(); j++) {
        ((Vector) outputVector.get(i)).add(mainVector.get(i).get(j));
    }
}

I have to point out that this seems very old school Java. Unless you have a legacy project, consider using something Vector<Vector<Object>> outputVector. Also you probably want to use List as Vector is now considered obsolete

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82