Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I sort a vector array??? 3

Status
Not open for further replies.

DCCoolBreeze

Programmer
Jul 25, 2001
208
US
I have a vector of class objects. Within the class object, I have several properties one of which is an integer. Is there a way I can sort the vector array relative to that specific integer property?

Example: Class Person
String fname
String lname
int age

Vector v = new Vector

v.add(...)
v.add(...)
v.add(...)

now sort v by age

Thanks for the help
 
An example:
Code:
import java.util.*;

public class SortedVector {

  static class Person implements Comparable {
    String name;
    String surname;
    int age;

    Person(String name, String surname, int age) {
      this.name = name;
      this.surname = surname;
      this.age = age;
    }
    public String toString() {
      return
        ("Name: "+name+
        "\nSurname: "+surname+
        "\nAge: "+age);
    }
    public int compareTo(Object o) {
      int age1 = ((Person) this).age;
      int age2 = ((Person) o).age;
      return (age1 - age2);
    }
  }

  public static void main(String[] args) {
    Vector v = new Vector();
    v.add( new Person( "John", "Smith", 20 ) );
    v.add( new Person( "Jane", "Doe",   30 ) );
    v.add( new Person( "Fred", "Black", 10 ) );
    Collections.sort(v);
    Enumeration e = v.elements();
    while(e.hasMoreElements()) {
      System.out.println(e.nextElement().toString());
    }
  }
}
Cheers, Neil :)
 
Thanks! Works great. Now I have one more question. What if I want to sometimes sort on one field in the class and then another field in the class. Say perhaps, sometimes age...sometimes lastname and sometimes both
 
Collections.sort is overloaded with a method that requires the user to supply an implementation of Comparator:

Collections.sort(Collection coll, Comparator comp);

The Comparator interface is defined as:
Code:
package java.util;
public interface Comparator {
  public abstract int compare(Object o1, Object o2);
  public abstract boolean equals(Object obj);
}

Therefore you can use code like:
Code:
import java.util.*;

public class SortedVector {

  static class Person {
    String name;
    String surname;
    int age;

    Person(String name, String surname, int age) {
      this.name = name;
      this.surname = surname;
      this.age = age;
    }
    public String toString() {
      return
        ("Name: "+name+
        "\nSurname: "+surname+
        "\nAge: "+age);
    }
  }

  public static void main(String[] args) {
    Vector v = new Vector();
    v.add( new Person( "John", "Smith", 20 ) );
    v.add( new Person( "Jane", "Smith", 30 ) );
    v.add( new Person( "Fred", "Black", 10 ) );
    Collections.sort(v, new Comparator() {
        // sort by surname, then age
        public int compare(Object o1, Object o2) {
          Person p1 = (Person) o1;
          Person p2 = (Person) o2;
          int res = p1.surname.compareTo(p2.surname);
          if(res != 0)
            return res;
          else
            return p1.age - p2.age;
        }
        public boolean equals(Object obj) {
          return this == obj;
        }
    });
    Enumeration e = v.elements();
    while(e.hasMoreElements()) {
      System.out.println(e.nextElement().toString());
    }
  }
}
Cheers, Neil :)
 
OK. Just one more question (do I sound like Columbo?). Is there a way to extract all objects that are the same in some way? For example, let's say that I want to move all objects whose age values are above 40 to another vector. I know that I can do this in about 6 lines but I noticed a method like copyAll that moves all objects in a Vector to another Vector.

or

Can I sort a vector using tags? for example, Let's say that I want to sort the Collection using the following tags in the order of the listing of the tags:

Germany, Alaska, North Pole.

Notice that they are not in alphabetical order.

I guess if I understood the logic behind sort I might be able to manipulate it to do the above

 
>> Can I sort a vector using tags?

In your implementation of Comparable.compareTo() you can compare whatever you like. Also you can have more than one <Comparable> implementation so you can sort the Vector in several different ways.


>> Is there a way to extract all objects that are the
>> same in some way?

Not how I would do this but for a school project it should be fine. You can use Hashtables for that by putting a Vector in each location and filling up the Vector.

Hashtable locations = new Hashtable();
locations.put(&quot;Germany&quot;, new Vector());
((Vector)locations.get(&quot;Germany&quot;)).add( new MyObject(...));
locations.put(&quot;North Pole&quot;, new Vector());
((Vector)locations.get(&quot;North Pole&quot;)).add( new MyObject(...));

Now if you are in an OOAD course you might want to consider deriving from Hashtable but that is another subject.

Good luck
-pete
 
I am looking at Hashtables now. The problem with Hashtables is they reference a unique key...say, I can have more than one John Smith who is 40. Now I can generate my own key but then would we not be back to Vectors? Actually, let me ask this? What would be the best practise methodology for a situation like this?
 
One approach to finding people within a certain age range.
Code:
  public static void main(String[] args) {
    Vector v = new Vector();
    v.add( new Person( &quot;a&quot;, &quot;z&quot;, 3 ) );
    v.add( new Person( &quot;b&quot;, &quot;y&quot;, 5 ) );
    v.add( new Person( &quot;c&quot;, &quot;x&quot;, 23 ) );
    v.add( new Person( &quot;d&quot;, &quot;w&quot;, 17 ) );
    v.add( new Person( &quot;e&quot;, &quot;v&quot;, 45 ) );
    v.add( new Person( &quot;f&quot;, &quot;u&quot;, 99 ) );
    v.add( new Person( &quot;g&quot;, &quot;t&quot;, 40 ) );
    v.add( new Person( &quot;h&quot;, &quot;s&quot;, 77 ) );
    v.add( new Person( &quot;i&quot;, &quot;r&quot;, 32 ) );
    v.add( new Person( &quot;j&quot;, &quot;q&quot;, 12 ) );
    v.add( new Person( &quot;k&quot;, &quot;p&quot;, 43 ) );
    v.add( new Person( &quot;l&quot;, &quot;o&quot;, 22 ) );
    v.add( new Person( &quot;m&quot;, &quot;n&quot;, 35 ) );

    Comparator byAge = new Comparator() {
        public int compare(Object o1, Object o2) {
          Person p1 = (Person) o1;
          Person p2 = (Person) o2;
          return p1.age - p2.age;
        }
    };

    Collections.sort(v, byAge);
    int min = Collections.binarySearch(v, new Person(&quot;&quot;,&quot;&quot;,40), byAge);
    int max = Collections.binarySearch(v, new Person(&quot;&quot;,&quot;&quot;,80), byAge);
    System.out.println(&quot;min: &quot;+min+&quot;, max: &quot;+max);
    min = (min < 0) ? -(min+1) : min;
    max = (max < 0) ? -(max+1) : max;
    System.out.println(&quot;min: &quot;+min+&quot;, max: &quot;+max);
    Iterator it = v.subList(min, max).iterator();
    while(it.hasNext())
      System.out.println(it.next().toString());
  }
See for information on the binarySearch method.

A similar thing can be done for a specific surname. See next post :)
 
And find all surnames beginning with &quot;J&quot;.
Code:
  public static void main(String[] args) {
    Vector v = new Vector();
    v.add( new Person( &quot;a&quot;, &quot;Smith&quot;, 10 ) );
    v.add( new Person( &quot;b&quot;, &quot;Smith&quot;, 10 ) );
    v.add( new Person( &quot;c&quot;, &quot;Smith&quot;, 10 ) );
    v.add( new Person( &quot;d&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;e&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;f&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;g&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;h&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;i&quot;, &quot;Jones&quot;, 10 ) );
    v.add( new Person( &quot;j&quot;, &quot;Flintstone&quot;, 10 ) );
    v.add( new Person( &quot;k&quot;, &quot;Flintstone&quot;, 10 ) );
    v.add( new Person( &quot;l&quot;, &quot;Flintstone&quot;, 10 ) );
    v.add( new Person( &quot;m&quot;, &quot;Flintstone&quot;, 10 ) );

    Comparator bySurname = new Comparator() {
        public int compare(Object o1, Object o2) {
          Person p1 = (Person) o1;
          Person p2 = (Person) o2;
          return p1.surname.compareTo(p2.surname);
        }
    };

    Collections.sort(v, bySurname);
    int min = Collections.binarySearch(v, new Person(&quot;&quot;,&quot;J&quot;,0), bySurname);
    int max = Collections.binarySearch(v, new Person(&quot;&quot;,&quot;K&quot;,0), bySurname);
    System.out.println(&quot;min: &quot;+min+&quot;, max: &quot;+max);
    min = (min < 0) ? -(min+1) : min;
    max = (max < 0) ? -(max+1) : max;
    System.out.println(&quot;min: &quot;+min+&quot;, max: &quot;+max);
    Iterator it = v.subList(min, max).iterator();
    while(it.hasNext())
      System.out.println(it.next().toString());
  }
Cheers, Neil :)
 
When I need to work with complex data using different methods to organize and extract data I look at using XML. The combination of XPath query results and XSLT transformations can provide a simple and powerful data mechanism.

&quot;But, that's just my opinion... I could be wrong&quot;.
-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top