Sort Vector

Hi Java gurues.
I need help for sorting a Vector.
I have the following Java code:
public class IeSection {
     public Vector stmtVector = null;
     private IeFuncStatements fs = null;
stmtVector.add(fs);
public class IeFuncStatements {
     private boolean istrue;
     private String func;
     private String name;
I want three possible ways to sort the Vector stmtVector dipending on
the field I select:
- by istrue
- by func
- by name
Thanks for any answers.
Geir

man if I was writing something as complex I would read all my posts and atleast try to see what they are saying......I did ask you to look at my previous post today which god damn explains with an example how to implement Comparator and even has links posted by some kind people to java docs!
Are you sure you should be writing such complex code??? ;-)

Similar Messages

  • Merging two sorted Vectors into one

    I wish to write a function that will accept two Vectors which are sorted and merge them into a single sorted Vector. I plan to use the compareTo() function to perform the comparisons between objects. I want the function to do this task for Vectors containing Integer, String, or any User Defined Classs (both the vectors will be containing objects of same class though).
    However, I am unable to do this because whether I use an iterator or write a loop to acces the elements of the Vector, I am required to typecast the returned object. I am using J2SE 1.4.2
    1 Vector mergeSortedVectors(Vector a, Vector b) {
    2         Vector c = new Vector();
    3         int p1=0, p2=0;
    4         while(p1<a.size() && p2<b.size()) {
    5                int result = ((Object)a.get(p1++)).compareTo((Object)b.get(p2++));
    6                // insertion logic
    7         }
    8 }Line no 5 gives me a compile error: Object.compareTo() not found
    Please help

    Cast it to Comparable instead of Object.

  • Sort Vector with quicksort & compareTo

    hmm, maybe someone could give me a hint.
    the code looks like this:
    Vector wbVec = new Vector(500,50); // filled with Stringobjects
    quickSort(wbVec);
         public void quickSort(Vector wbVec){
              sort(wbVec,0,(wbVec.size()-1));
         public void sort(Vector wbVec, int links, int rechts){
              int auf = links;
              int ab = rechts;
              final Object ausgewaehlt = wbVec.elementAt((links+rechts)/2);
              do{
                   while(wbVec.elementAt(auf).compareTo(ausgewaehlt)){
                        auf++;
                   while(ausgewaehlt.compareTo(wbVec.elementAt(ab))){
                        ab--;
                   if(auf<=ab){
                        final Object temp = wbVec.elementAt(auf);
                        wbVec.setElementAt(wbVec.elementAt(ab),auf);
                        wbVec.setElementAt(temp,ab);
                        auf++;
                        ab--;
              }while(auf<=ab);
              if(links < ab){
                   sort(wbVec,links,ab);
              if(auf < rechts){
                   sort(wbVec,auf,rechts);
    the compiler just says "cannot resolve symbol: method compareTo"
    first: why? i probably got the crap all wrong but please gimme a hint
    2nd: what shall i change to make it work?
    pleeaaassee!!! i am still new to this stuff so i am sorry in case my questions are completely stupid :)

    the compiler just says "cannot resolve symbol: method compareTo"
    first: why? i probably got the crap all wrong but please gimme a hint
    2nd: what shall i change to make it work?As far as the compiler's concerned, "wbVec.elementAt(auf)" is of type Object, and Object doesn't have a compareTo method. You'll need to do ((Comparable)wbVec.elementAt(auf)) instead.

  • Sort vector by file or folder

    I have a vector that is returning a directory and all of its contents (files and folders). I need to sort it so the folders will be listed first then the files. I believe I have to comparison but am not sure how. I am very new to java so examples would be great.
    tks

    You need to either implement Comparable.compareTo or Comparator.compare.
    The comparison method will first check the types of the objects. If one is a folder and one is a file, have it return 1 or -1, depending on which was which.
    If they're both files or both folders, then you return the results of comparing their names (or whatever other attirbute you want to sort on).
    http://www.onjava.com/lpt/a/328

  • How do you sort vector descendingly?

    Lets say if have a vector which contains values in double data type.
    Vector vNum = ne wVector();
    vNum.addElement(new Double("50.5"));
    vNum.addElement(new Double("40.5"));
    vNum.addElement(new Double("60.5"));_______________________________________
    If you sort it ascendingly by entering the code:
    Collections.sort(vNum);The result would be
    40.5
    50.5
    60.5
    and it is correct. But i tried to sort it descendingly by entering the code:
    Collections.reverse(vNum);The result was:
    60.5
    40.5
    50.5
    Someone told me before that the code for sorting descendingly was Collections.reverse(vectorName); but it didnot work.
    Does anyone know what's the code for sorting the Vector descendingly?
    thanks!

    Collections.reverse(list) just reverses the order of the elements in the specified list.
    You can either call sort() and then reverse(), or you can specify your own Comparator for sorting in reverse order. (I prefer the second solution)
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

  • Sort Vector Art from Bitmaps

    Hi,
    I have a folder containing over 2000 eps files and need to separate these into raster images and those containing vectors.
    The script I am using opens each file in turn and uses the first layer name to determine if the file has been rasterised or not. If not then I update some meta data and close and save the file. If the layer name is "layer 1" I assume the file has vector artwork and has been rasterised, I then close the file without saving changes.
    ____________ the script__________
    var samplesFolder = Folder("J:/Extracted_Standing_Artwork/Non_Customer")
    var fileList = samplesFolder.getFiles("*.eps");
    for (var i = 0; i < fileList.length; i++) {
    if (fileList[i] instanceof File) {
    var fileRef = new File(fileList[i]);
    app.open( fileRef, );
    var layer = app.activeDocument.activeLayer.name;
    var filePath = decodeURI(app.activeDocument.path);
    var fileName = decodeURI(app.activeDocument.name);
    if (layer=="Layer 1"){
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
    else{
    app.activeDocument.info.author = "Bitmap"
    epsSaveOptions = new EPSSaveOptions()
    app.activeDocument.close(SaveOptions.SAVECHANGES)
    __________ end ____________
    The result is raster files in the folder with a very recent modified date and untouched vector files.
    Can anyone please suggest a better way of doing this.
    It is possible to test for the "Rasterize Generic EPS Format" dialog box?
    Can a javascript then "move" the vector files into a new folder to leave just the rasters in the orginal folder.
    Any help would be appreciated.
    Simon Kemp

    Line 1 defines the function.
    line 2 sets the file object from the argument to the var test. This line is not really needed, I could have just used the file argument. It's likely a hold over from a previous edit.
    Line 3 opens the file in read mode.
    Line 4 reads the entire file and assigns it to str.
    Line 5 closes the file for good housekeeping.
    Line 6 search the string in str for 'Adobe Photoshop' and assigns the result to res. res will either be -1 if not found or the start position in the str if it was found.
    Line 7 tests the contents of res and either returns true or false. This line could be rewritten as an if statement
    if( res == -1){
    res = true;
    }else{
    res = false;
    return res;
    Line 8 closes off the function block.
    Hope that helps

  • Need to sort two vectors at the same time! please help!

    I have
    vectorA: 2 4 9 1 7 6 8
    vectorB: two four nine one seven six eight
    i want to sort these two vectors in parallel
    what is the best way?
    i could just do Collection.sort(vectorA) and get
    1 2 4 6 7 8 9
    but i want the vectorB to have a corresponding order
    please help!!
    thanks

    public class Pair implements Comparable {
    private int value;
    private String name;
    public int getValue() {
    return this.value;
    public void setValue(int value) {
    this.value = value;
    public String getName() {
    return this.name;
    public void setName(String name) {
    this.name = name;
    public int compareTo(Object o) {
    Pair that = (Pair) o;
    return this.value - that.value;
    place both in a Collection (vector is a bad choice if you are going to do sorting LinkedList is better) the Collections.sort method will sort
    according to the compareTo method.

  • Sorting Arrays in a Vector by a String field in the array

    Hi
    i have a Vector where i put Arrays in. These Arrays are all of the same type. The first field is kind of an indetifier, the type is String. That's the key field i'd like to sort the vector elements in an alphabetical order.
    I know there is that Collator methode to sort Vectors. That's no problem for me to do if i just have Strings in the Vector. But with this contruct of Arrays that need do be sortet for one fiel of the array, i have no idea whether this might be done with that Collator methode too.
    So, before i start written some kind of bubble sort methode (that sure would solve the problem, but probably not very smart and fast...) I'd like to ask you, whether you have an idea how to solve that problem with Collator or even with some other methode?
    thanks for your help!

    Comparable and Arrays.sort. Read the APIs, or look at the two or three examples I've done so far today in this forum. Or search the forum for +Comparable Arrays sort
    Answer provided by Friends of the Water Cooler. Please inform forum admin via the
    'Discuss the JDC Web Site' forum that off-topic threads should be supported.

  • Sort a vector of objects by one of its attributes

    Hi all!
    I have created this class:
    public class Client {
    private int numero;
    private double tempsEntrada;
    private double tempsServei;
    private double tempsIniciSessio;
    private char tipus;
    * Creates a new instance of Client
    public Client(int num, double temp,double servei, char tip) {
    numero = num;
    arrivalTime = temp;
    serviceTime = servei;
    tipus = tip;
    public char getTipus()
    return tipus;
    public int getNumero()
    return numero;
    public double getTempsEntrada()
    return arrivalTime;
    public double getTempsServei()
    return serviceTime;
    Now I've done a java vector of this object, and I want to sort it by arrivalTime.
    The class comparer looks like this
    public class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    double temps1 = ((Client)obj1).getTempsEntrada();
    double temps2 = ((Client)obj2).getTempsEntrada();
    return (int)(temps1 - temps2);
    now when I do Collections.sort(vector);
    this is the error reported:
    Exception in thread "main" java.lang.ClassCastException: cafevirtual.Client cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.sort(Arrays.java:1079)
    at java.util.Collections.sort(Collections.java:117)
    at cafevirtual.Main.main(Main.java:76)
    Java Result: 1
    what's wrong?
    thanks!

    Your Client class does not implement Comparable. You have to specify the Comparator to use: Collections.sort(vector, new Comparer());

  • Compile error when using Collections.sort for Vector, why?

    The compiler is giving an error when trying to do this (I'm using JDK 1.5.0_09):
    Vector <String> test = new Vector <String>();
    test.add("test1");
    test.add("test2");
    test.add("test3");
    Collections.sort(test);The error being:
    The method sort(Vector<String>) is undefined for the type Collections
    Collections.sort takes List, but Vector is of type List, so this should work, correct?

    ChuckBing wrote:
    No. Vector is not a subclass of List. Use List.um.. Vector implements List

  • Sorting a Vector by position in Alphabet

    Hey Folks,
    I have a Vector containing pairs of letters. e.g.
    ad
    ac
    de
    be
    bd
    Is it possible to sort the Vector by position in the Alphabet i.e. pairs beginning with 'a' are first, then those starting with 'b' etc... So would end up with something like:
    ac
    ad
    bd
    be
    de
    I'm not too bothered about the position of the second letter but would be a bonus if it was taken into consideration!
    Any help or suggestions would be great thanks.

    Please note that the code given sorts by Unicode value of the characters in the Strings (e.g. capital Z appears before lowercase a), NOT alphabetically. This may or may not be what you want.
    If you want to sort alphabetically (and/or for a specific locale), use a Collator as the second argument for the sort:Collections.sort(vector, Collator.getInstance(); // default locale of your machineorCollections.sort(vector, Collator.getInstance(Locale.US); // specific locale: US English

  • Sorting a vector

    hi
    all i am having problem with sorting a vector.I have a vector which contain Objects and each object has string values
    Vector->Objects->String 1 string 2 string 3;
    now i want to sort by string 2 but i also want to sort it by string 3 i means vector should be able to sort by string 2 and second preriority to string 3 and then string1.
    How can i do this i am over loading the comparator class.
    Collection.sort(vector, new vecComparetor());
    public int compare(Object obj1, Object obj2) {
    retrun obj1.compareTo(obj2);
    }

    If I guessed correctly your class is something like the following:
    package mydomain;
    public class MyClass{
         private String str1, str2, str3;
         public MyClass( String str1, String str2, String str3){
              this.str1 = str1;
              this.str2 = str2;
              this.str3 = str3;
         public String getStr1(){ return str1;}
         public String getStr2(){ return str2;}
         public String getStr3(){ return str3;}
         public String toString(){ return "(" + str1 + ", " + str2 + ", " + str3 + ")";}
    }Now, your problem is: Order Vector of MyClass objects by str2, then by str1, then by str3.
    So here it is your Comparator:
    package utils;
    import mydomain.MyClass;
    import java.util.Comparator;
    public class MyComparator implements Comparator{
         public int compare( Object o1, Object o2){
              int i = 0;
              return (i = ((MyClass)o1).getStr2().compareTo( ((MyClass)o2).getStr2())) != 0? i:
                    ((i = ((MyClass)o1).getStr1().compareTo( ((MyClass)o2).getStr1())) != 0? i:
                    ((i = ((MyClass)o1).getStr3().compareTo( ((MyClass)o2).getStr3())) != 0? i: 0));
    }Try it out with this tester (cut and paste these three classes. They compile and run.):
    package utils;
    import mydomain.MyClass;
    import java.util.Vector;
    import java.util.Collections;
    public class MyComparatorTest{
         public static void main( String[] args){
              Vector v = new Vector();
              for( char x = 'a'; x <= 'c'; x++){
                   for( char y = 'a'; y <= 'c'; y++){
                        for( char z = 'a'; z <= 'c'; z++){
                             v.add( new MyClass( new Character( x).toString(), new Character( y).toString(), new Character( z).toString()));
              System.out.println( v);
              Collections.sort( v, new MyComparator());
              System.out.println( v);
    }

  • Vector Sorting w/multiple fields

    I've looked through some of the previous postings on sorting vectors. But most of what I've seen are solutions to vectors with objects which hold one string. But what if you have, say an identity object which holds a person's full name, address and zip? After storing each object in a vector, simply using ( Collections.sort( ) ) can't possibly work.
    How would calling that method know whether you want to sort by first name, or last name or by zip?
    Thanks in advance for your help.

    Thats why you need either a Comparator class you can use with the sort method to tell how to objects are compared, or implement Comparable in the class holding the persons name, address, etc.
    Check the API for
    java.util.Comparator
    java.lang.Comparable

  • Sorting the Rows in a JTable Component Based on a Column

    Hi Masters..would like to have your valuable help and suggestion..i am using jdk1.4.i have jtbale and would like to have one column data in sorted way...
    just i am enclosing my code in tha i am using Collections.sort(data, new ColumnSorter(colIndex, ascending)); but that compare of that comparator is not at woring that data is not getting soretd.
    here data is the jtable complete data.
    Main java file:
    package com.ibm.sort;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class SimpleTableDemo extends JPanel {
    private boolean DEBUG = false;
         int colIndex;
              boolean ascending;
         DefaultTableModel model = new DefaultTableModel();
    public SimpleTableDemo() {
    super(new GridLayout(1,0));
    String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
    Object[][] data = {
    {"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 80));
              table.setAutoCreateColumnsFromModel(false);
         JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
              sortAllRowsBy(model, 1, true);
         public void sortAllRowsBy(DefaultTableModel model, int colIndex, boolean ascending) {
                   Vector data = model.getDataVector();
                   System.out.println("SimpleTableDemo.sortAllRowsBy()11111");
                   Collections.sort(data, new ColumnSorter(colIndex, ascending));
              //Collections.sort(data);
                   //Arrays.sort(data, new ColumnSorter(colIndex, ascending));
                   System.out.println("SimpleTableDemo.sortAllRowsBy()2222");
                   model.fireTableStructureChanged();
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SimpleTableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    SimpleTableDemo newContentPane = new SimpleTableDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Second FIle which has sorting :
    * Created on Jun 21, 2008
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package com.ibm.sort;
    import java.util.Comparator;
    import java.util.Vector;
    // This comparator is used to sort vectors of data
    public class ColumnSorter implements Comparator {
         int colIndex;
         boolean ascending;
         ColumnSorter(int colIndex, boolean ascending) {
              System.out.println("ColumnSorter.ColumnSorter(---colIndex--:"+colIndex+" ,ascending: "+ascending);
              this.colIndex = colIndex;
              this.ascending = ascending;
              System.out.println("ColumnSorter.ColumnSorter()");
         public int compare(Object a, Object b) {
              System.out.println("compare-----:");
              Vector v1 = (Vector)a;
              Vector v2 = (Vector)b;
              Object o1 = v1.get(colIndex);
              Object o2 = v2.get(colIndex);
    System.out.println("ColumnSorter.compare(): -o1- :"+o1+" ,o2: "+o2);
              // Treat empty strains like nulls
              if (o1 instanceof String && ((String)o1).length() == 0) {
                   o1 = null;
              if (o2 instanceof String && ((String)o2).length() == 0) {
                   o2 = null;
              // Sort nulls so they appear last, regardless
              // of sort order
              if (o1 == null && o2 == null) {
                   return 0;
              } else if (o1 == null) {
                   return 1;
              } else if (o2 == null) {
                   return -1;
              } else if (o1 instanceof Comparable) {
                   if (ascending) {
                        System.out.println("ascending-->ColumnSorter.compare()-((Comparable)o1).compareTo(o2): "+(((Comparable)o1).compareTo(o2)));
                        return ((Comparable)o1).compareTo(o2);
                   } else {
                        System.out.println("Desending-->ColumnSorter.compare()-((Comparable)o1).compareTo(o2): "+(((Comparable)o1).compareTo(o2)));
                        return ((Comparable)o2).compareTo(o1);
              } else {
                   if (ascending) {
                        System.out.println("ColumnSorter.compare()---o1.toString().compareTo(o2.toString())---: "+(o1.toString().compareTo(o2.toString())));
                        return o1.toString().compareTo(o2.toString());
                   } else {
                        return o2.toString().compareTo(o1.toString());
    Please help is deadly needed.
    thanks in advance!!!

    Learn to use code tags.
    Learn to use google.
    http://www.google.com/search?q=java+sort+rows+jtable&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

Maybe you are looking for

  • Wireless mouse and keyboard Windows 7

    I successfully installed Windows 7 (32 bit) on Apple boot camp (3.2) of my iMac 24. Everything is working perfectly, except my wireless Magic mouse and wireless keyboard. I found 2 Bluetooth adapters (Generic Bluetooth adapter and Microsoft Bluetooth

  • Thread in Swing help please

    Hey gang, I am relatively new to Java world, and especially to swing and thread. I am trying to build an application with a main dashboard, where the users can click on a button and parse a text file. However, if there were an error in the file, I wo

  • Data convertion while exporting data into flat files using export wizard in ssis

    Hi , while exporting data to flat file through export wizard the source table is having NVARCHAR types. could you please help me on how to do the data convertion while using the export wizard? Thanks.

  • XY Graph Differences

    Sorry for such a simple question, but what's the difference between the XY Graph and Classic XY Graph?  The only thing I can see is the Classic has the flat-style look, which I prefer, and the regular has the raised-curved look.  Is there anything el

  • Sharing XML file between computers?

    I've just set up all the computers in my house to put all new imports onto the same external hardrive, but i realised that this doesn't update all of the computers' itunes libraries, just the one that the songs were imported through. I was trying to