Sorting two dimensional Vector...
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Madhan_Prabahar
Posted On:   Wednesday, July 23, 2003 10:19 PM

Please go through the following code snipet... Vector vec = new Vector(); Vector vec1 = new Vector(); vec1.add("Good"); vec1.add(new Integer(100)); Vector vec2 = new Vector(); vec2.add("Bad"); vec2.add(new Integer(50)); Vector vec3 = new Vector(); vec3.add("Ugly"); vec3.add(new Integer(10)); vec.add(vec3); vec.add(vec1); vec.add(vec2); System.out.println(vec); //Out put::[[Ugly, 10],[Good, 100],[Bad, 50]] I want to sort(descending order) the elements (inner vetors) of the vector 'vec' based on the second element(integer) of inn   More>>


Please go through the following code snipet...


			
Vector vec = new Vector();

Vector vec1 = new Vector();
vec1.add("Good");
vec1.add(new Integer(100));

Vector vec2 = new Vector();
vec2.add("Bad");
vec2.add(new Integer(50));

Vector vec3 = new Vector();
vec3.add("Ugly");
vec3.add(new Integer(10));

vec.add(vec3);
vec.add(vec1);
vec.add(vec2);


System.out.println(vec);
//Out put::[[Ugly, 10],[Good, 100],[Bad, 50]]




I want to sort(descending order) the elements (inner vetors) of the vector 'vec' based on the second element(integer) of inner vectors...






The desired out put::[[Good, 100], [Bad, 50], [Ugly, 10]]

How to do this...?





Thanks


Madhan
   <<Less

Re: Sorting two dimensional Vector...

Posted By:   Stephen_McConnell  
Posted On:   Thursday, July 24, 2003 05:10 AM

I'm trying to understand why?


The data structure you are using mixes the metaphors. You should have one vector for the Strings and one for the numbers, then place those two vectors in the parent container.


If you are set on using Vectors, here's a better way to do this.


Vector outerVector = new Vector();

Vector innerVector1 = new Vector();
Vector innerVector2 = new Vector();

innerVector1.add("Good");
innerVector1.add("Bad");
innerVector1.add("Ugly");

innerVector2.add(new Integer(10));
innerVector2.add(new Integer(50));
innerVector2.add(new Integer(100));

outerVector.add(innerVector1);
outerVector.add(innerVector2);



Now you can use the collections sort to sort the second and first vectors any way you want.


The movement of innerVector1 is not tied to the movement of innerVector2.


You might want to get a book on Data Structures in Java, however. Then, you would see about 100 better ways to do this.


Stephen McConnell

About | Sitemap | Contact