Vector sorting help

hi, im trying to figure out how to sort the vector objects below in alphabetical order. But i can't figure out how to fix this code
any help is greatly appreciated. THANKS!!!
import java.lang.String.*;
import java.util.Vector;
public class Test2
public void hi()
Vector v = new Vector();
v.add("Donkey");
v.add("Dog");
v.add("Parakeet");
v.add("Cat");
v.add("Mule");
v.add("Horse");
v.add("Zebra");
v.add("Lion");
v.add("Frog");
v.add("Catepillar");
v.add("Butterfly");
v.add("Ostrich");
for(int i = 0; i < v.size(); i++)
int o = i;
int j = i - 1;
while(j>=0 && j > o)
v.get(j + 1) = v.get(i);
j--;
j + 1 = o;
//substring(s.indexOf(",") + 2, s.indexOf("[") - 1)
}

hi, im trying to figure out how to sort the vector
objects below in alphabetical order. But i can't
figure out how to fix this code
any help is greatly appreciated. THANKS!!!
import java.lang.String.*;
import java.util.Vector;
public class Test2
public void hi()
Vector v = new Vector();
v.add("Donkey");
v.add("Dog");
v.add("Parakeet");
v.add("Cat");
v.add("Mule");
v.add("Horse");
v.add("Zebra");
v.add("Lion");
v.add("Frog");
v.add("Catepillar");
v.add("Butterfly");
v.add("Ostrich");
for(int i = 0; i < v.size(); i++)
int o = i;
int j = i - 1;
while(j>=0 && j > o)
v.get(j + 1) = v.get(i);
j--;
j + 1 = o;
//substring(s.indexOf(",") + 2, s.indexOf("[") -
) - 1)
}Hi!
You can't do:
v.get(j + 1) = v.get(i);
I think what you want to do is:
v.set(j+1,v.get(i));
Read this:
"set
public Object set(int�index,Object�element)
Replaces the element at the specified position in this Vector with the specified element."
If you have other questions, just say!
Hope it helps!!!
Regards,
ACN

Similar Messages

  • Complicated Sort help

    I am try to sort a table of 3 columns and many rows. each row's data have to be in tact. But I would like to sort the first column's data (assuming strings) in ascending order. Then given that, sort the second column with decending order. Then sort the third column with acsending again. or any combinations. How to accomplish this in Java? what is the best logic or tool i should use? arrary of array? or collection? etc...
    any help is appricated!!!
    example:
    (before sort)
    apple 5 red
    watermelon 2 green
    pear 10 yellow
    (after sort first iteration)
    apple 5 red
    pear 10 yellow
    watermelon 2 green
    (after sort 2nd iteration)
    watermelon 2 green
    apple 5 red
    pear 10 yellow
    (third and final result)
    watermelon 2 green
    apple 5 red
    pear 10 yellow
    thanks

    I am doing something similar in my application. I am using a JTable.
    On mouse click on a column header i do the following:
    <code>
    -----Method inside the class having the JTable
    protected void sortAllRowsBy(DefaultTableModel model, int colIndex, boolean ascending)
    data = model.getDataVector();
    Collections.sort(data, new ColumnSorter(colIndex, ascending));
    model.fireTableStructureChanged();
              data=null;
    ------ColumnSorter.java
    import java.util.Vector;
    import java.util.Comparator;
    public class ColumnSorter implements Comparator
    int colIndex;
    boolean ascending;
    ColumnSorter(int colIndex, boolean ascending)
    this.colIndex = colIndex;
    this.ascending = ascending;
    public int compare(Object a, Object b)
    Vector v1 = (Vector)a;
    Vector v2 = (Vector)b;
    Object o1 = v1.get(colIndex);
    Object o2 = v2.get(colIndex);
    // 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)
                             try
                                  Double d1=Double.valueOf(o1.toString());
                                  Double d2= Double.valueOf(o2.toString());
                                  return d1.compareTo(d2);
                             catch(Exception e)
                                  // LogFileWriter.writeTextInFile("Exception occured in ColumnSorter: "+ e.toString());
                                  return ((Comparable)o1).compareTo(o2);
                        else
                             try
                                  Double d1=Double.valueOf(o1.toString());
                                  Double d2= Double.valueOf(o2.toString());
                                  return d2.compareTo(d1);
                             catch(Exception e)
                                  // LogFileWriter.writeTextInFile("Exception occured in ColumnSorter: "+ e.toString());
                                  return ((Comparable)o2).compareTo(o1);
                   else
                        System.out.println("not comparable");
    if (ascending)
    return o1.toString().compareTo(o2.toString());
                        else
    return o2.toString().compareTo(o1.toString());
    </code>

  • 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

  • How do I  print out the attributes of objects from a  Vector?  Help !

    Dear Java People,
    I have created a video store with a video class.I created a vector to hold the videos and put 3 objects in the vector.
    How do I print out the attributes of each object in the vector ?
    Below is the driver and Video class
    Thank you in advance
    Norman
    import java.util.*;
    public class TryVideo
    public static void main(String[] args)
    Vector videoVector = new Vector();
    Video storeVideo1 = new Video(1,"Soap Opera", 20);
    Video storeVideo2 = new Video(2,"Action Packed Movie",25);
    Video storeVideo3 = new Video(3,"Good Drama", 10);
    videoVector.add(storeVideo1);
    videoVector.add(storeVideo2);
    videoVector.add(storeVideo3);
    Iterator i = videoVector.interator();
    while(i.hasNext())
    System.out.println(getVideoName() + getVideoID() + getVideoQuantity());
    import java.util.*;
    public class Video
    public final static int RENT_PRICE = 3;
    public final static int PURCHASE_PRICE = 20;
    private int videoID;
    private String videoName;
    private int videoQuantity;
    public Video(int videoID, String videoName, int videoQuantity)
    this.videoID = videoID;
    this.videoName = videoName;
    this.videoQuantity = videoQuantity;
    public int getVideoID()
    return videoID;
    public String getVideoName()
    return videoName;
    public int getVideoQuantity()
    return videoQuantity;
    }

    Dear Bri81,
    Thank you for your reply.
    I tried the coding as you suggested
    while(i.hasNext())
    System.out.println( i.next() );
    but the error message reads:
    "CD.java": Error #: 354 : incompatible types; found: void, required: java.lang.String at line 35
    Your help is appreciated
    Norman
    import java.util.*;
    public class TryCD
       public static void main(String[] args)
         Vector cdVector = new Vector();
         CD cd_1 = new CD("Heavy Rapper", "Joe", true);
         CD cd_2 = new CD("Country Music", "Sam", true);
         CD cd_3 = new CD("Punk Music", "Mary", true);
         cdVector.add(cd_1);
         cdVector.add(cd_2);
         cdVector.add(cd_3);
         Iterator i = cdVector.iterator();
         while(i.hasNext())
           System.out.println( i.next() );
    public class CD
       private String item;
       private boolean borrowed = false;
       private String borrower = "";
       private int totalNumberOfItems;
       private int totalNumberOfItemsBorrowed;
       public CD(String item,String borrower, boolean borrowed)
         this.item = item;
         this.borrower = borrower;
         this.borrowed = borrowed;
       public String getItem()
         return item;
       public String getBorrower()
         return borrower;
       public boolean getBorrowed()
         return borrowed;
       public String toString()
          return System.out.println( getItem() + getBorrower());

  • Movie Library, sorting HELP!!!

    I recently converted home movies and imported them to itunes. One thing that I notice is I can't sort them alphabetically. There is no rhyme or reason to the way that itunes sorts the movie titles. I am familiar with sorting by genre, name, time, etc. etc. but even then itunes does not sort them properly.
    I.e. Genre, then alphabetically.
    In addition I can't add a description, or movie rating to the file.
    Now the purchased movies from itunes seem to organize properly, which might have something to do with the files it self. Who knows? Can anyone help me figure this out?
    Thanks for your help
    CaSandra

    Figured it out..
    Thanks anyway

  • Radix sort help needed

    Can someone please help me with this radix sort on a dictionary (linkedList from the java utils). I am trying to pass the linkedList into an array which the java apis say that you can do with the to.Array() method but I am getting the noninformative cannot resolve symbol. Like the theory here is that one I should be able to pass a linkedList into an array and two, that I should be able to sort the list by calling the substrings(1,MAX_LENGTH) and then do a minus one on the length for the recursive call. However, this is giving me fits at this point and I don't know if I am totally off track and this will never work or if I am just not thinking it through clearly.
    Any help at all would be appreciated greatly...
    import java.util.*;
    public class radixSort
      //  radix sort using linked lists, where radixSort is not
      //  a method of the LinkeList class.
       public void radixSort(LinkedList listA)
       //*******************this is the line that's giving me fits***********************/
       java.util.LinkedList[] objArray = listA.toArray();
       final int MAX_LENGTH  =  8;    //  Strings are no more than 8 characters
       final int RADIX_SIZE = 26;    //  Alphabet has 26 letters
       // Use an array of 26 ArrayLists to groups the elements of the array
       createQueue[] groups = new createQueue[RADIX_SIZE];
       for (int x = 0; x < MAX_LENGTH; x++)
                 for (int i; i < MAX_LENGTH; i++)
                 groups = new createQueue();
              for (int position=MAX_LENGTH; position < 0; position--)
    for (int scan=0; scan < MAX_LENGTH; scan++)
    //ListIterator iter1 = listA.listIterator();
    String temp = String.valueOf (listA[scan]);
    String letter = temp.substring(0, position);
    groups[letter].enqueue ((listA[scan]));
    // gather numbers back into list
    int num = 0;
    for(int d=0; d<MAX_LENGTH; d++)
    while (!(groups[d].isEmpty()))
    numObj = groups[d].dequeue();
    listA[num] = numObj.intValue();
    num++;
    //****************************Here is the createQueue class...***********************/
    public class createQueue
    * Construct the queue.
    public createQueue( )
    front = back = null;
    * Test if the queue is logically empty.
    * @return true if empty, false otherwise.
    public boolean isEmpty( )
    return front == null;
    * Insert a new item into the queue.
    * @param x the item to insert.
    public void enqueue( Object x )
    if( isEmpty( ) ) // Make queue of one element
    back = front = new ListNode( x );
    else // Regular case
    back = back.next = new ListNode( x );
    * Return and remove the least recently inserted item
    * from the queue.
    public Object dequeue( )
    if( isEmpty( ) )
    //throw new UnderflowException( "ListQueue dequeue" );
              System.out.println("No elements");
    else;
    Object returnValue = front;
    front = front.next;
    return returnValue;
    * Get the least recently inserted item in the queue.
    * Does not alter the queue.
    public Object getFront( )
    if( isEmpty( ) )
    System.out.println("No elements");
    else;
    return front;
    * Make the queue logically empty.
    public void makeEmpty( )
    front = null;
    back = null;
    private ListNode front;
    private ListNode back;
    private void printans()
         if (isEmpty())
         System.out.println("No elements");
         else
         while (back != front)
         System.out.println (front);
         //front++;

    java.util.LinkedList[] objArray = listA.toArray();Impossible! You are going to convert a LinkedList to an array of LinkedList. It's impossible! Or, sheer nonsense, if ever possible.

  • Radix sort help again

    I created a linked list and are now trying to pass a word into a radix sort (which works outside of this particular program) so that it will sort the words and place them back into the appropriate places in the list. Just for the record, I haven't rewritten the part where it adds the sorted words back into the list so I know that part won't work right at the moment. I just need a work around for this error...
    java:197: non-static variable head cannot be referenced from a static context
    Here is the code...(does not include main cause main is long and complicated but it does work G)
    import java.util.Vector;
    public class neverishDictionary
        private Node head;
        public neverishDictionary()
             head = null;
        //begin inner node class
        private class Node
             private String word, pos, def, date, org;
             private Node next;
             public Node(String word1, String pos1, String def1, String date1, String org1)
             //1st constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = null;
            public Node(String word1, String pos1, String def1, String date1, String org1, Node nextNode)
            //2nd constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = nextNode;
            public String getWord()
                return word;
            public String getPos()
                return pos;
            public String getDef()
                return def;
            public String getDate()
                return date;
            public String getOrg()
                return org;
            public void setNext(Node nextNode)
                next = nextNode;
            public Node getNext()
                return next;
       }//ends the inner class
       public boolean isEmpty()
            return head == null;
       public void add(String newWord, String newPos, String newDef, String newDate, String newOrg)
            Node curr;
            Node prev;
            Node newNode = new Node (newWord, newPos, newDef, newDate, newOrg);
            if(isEmpty())
                newNode.setNext(head);
                head=newNode;
            else if(newWord.compareTo(head.getWord())<0)
                newNode.setNext(head);
                head=newNode;
            else
                prev = head;
                curr = head;
                while (curr != null)
                  if (newWord.compareTo(curr.getWord())<0)
                      prev.setNext(newNode);
                      newNode.setNext(curr);
                      break;
                   else
                       prev = curr;
                       curr = curr.getNext();
                       if (curr == null)
                           prev.setNext(newNode);
      public static Vector radixSort(Vector str1, Node prev, Node curr)
       Vector result = (Vector) str1.clone();
       final int MAX_LENGTH  =  8;    //  Strings are no more than 8 characters
       final int RADIX_SIZE = 26;    //  Alphabet has 26 letters
       int position = RADIX_SIZE;
       // Use an array of 26 ArrayLists to groups the elements of the array
        prev = null;
        curr = head;  // This is the line giving me fits and I'm not quite sure how to get around it.
        String str = curr.getWord();
       Vector[] buckets = new Vector[RADIX_SIZE];
        for (int i = 0; i < RADIX_SIZE; i++)
          buckets[i] = new Vector();
        int length = MAX_LENGTH;
        // Step through the positions from right to left, shoving into
        // buckets and then reading out again
        for (int pos = length-1; pos >=0; pos--) {
          // Put each string into the appropriate bucket
          for (int i = 0; i < MAX_LENGTH; i++) {
            str = (String) result.get(i);
            int bucketnum;
            // If the string is too short, shove it at the beginning
            if (str.length() <= pos)
              bucketnum = 0;
            else
              bucketnum = str.charAt(pos);
            buckets[bucketnum].add(str);
          // Read it back out again, clearing the buckets as we go.
          result.clear();
          for (int i = 0; i < MAX_LENGTH; i++) {
            result.addAll(buckets);
    buckets[i].clear();
    } // for(i)
    } // for(pos)
    // That's it, we're done.
    return result;
    } // sort

    Hello.
    As the error says, you are referencing a non-static member within a static function. Do a little reading on static functions. Basically you are assigning head to curr, but head has not been created yet, so the compiler is telling you it is a problem.

  • Indesign CS6 very slow with vectors. please Help!

    We updated to CS6 from CS5.5 to a Mac Pro running OS 10.6. Processors are 2 x 2.8 GHz Quad-Core Intel Xeon. Ram is 10 GB 800 MHz DDR2. Video card is ATI Radeon HD 2600 256 MB. One Cinema Display and a smaller Samsung monitor.
    The performance of InDesign when handling groups of vector files created inside InDesign is horrible. For example, I took a little 3 x 3px square and created a grid of 60 squares approx. When I select all of them (pure vectors) and try to move them it takes InDesign 10 seconds to respond to the selection first, and then 10 more seconds to move them.
    Another example, I created a very simple graph, pure vector of course, with a moderate number of text and lines and when I select the whole thing the lag comes again, takes a lot to mark the selection and then is very hard to move it.
    We have tweaked InDesign preferences (Interface, File Handling) as much as we could but the issue remains. We didn't have any problems with 5.5.
    Help please!

    had to install mountain lion and now everything works smoothly

  • URGENT SORT HELP NEEDED

    Hey everyone...
    This is VERY time critical....
    Could someone give me a method that uses an Insertion Sort to sort an array of Strings??
    Please help!!!
    Thanks!!
    Lardiop

    Object[] arr = new Object[size];
    Object temp1;
    for(int i=2; i <= arr.length; i++) {
      for(int j=i-1; j > 0; j--) {
        if(arr[j].compareTo(arr[j - 1]) < 0) {
          temp1 = arr[j];
          arr[j] = arr[j - 1];
          arr[j - 1] = temp1;
    }

  • Vector Shape Help

    I am trying to draw a circle within a circle an have polka dots around it like numbers five and four.  How do I get them to be even?  Do you think this person used a brush?  How do I get the shape in number 6 and 7?  How do get the rectangle shapes in number 8?  Also, when I create a circle and then another circle inisde of it, how do I make sure that they are evenly spaced?  When I print the shapes are way off?  I would appreciate any help I can get to mimick some of these designs.
    Thank You!!!

    I concur with Doug.
    But if you want to do it in Photoshop I recommend using Smart Objects of opposing pairs of elements, duplicating and numerically rotating those by the necessary angle:
    As for circles with the same center: create a vector circle Shape (with the Ellipse Tool), mark it, copy, paste, hit command-T and with alt-shift pressed scale it (or set the »Reference point location« in the Options Bar to center, click »Maintain aspect ratio« and enter a new value for width or height).

  • Keeping a Vector sorted as it is added to

    Hi,
    I have a class which extends Vector, and the elements of this Vector are long[]'s. For example
    Vector v = new Vector();
    long[] a = new long[] {10, 0, 0};
    long[] b = new long[] {3, 0, 0};
    long[] c = new long[] {7, 0, 0};
    v.add(a);
    v.add(b);
    v.add(c);As I add elemetns to my custom vector I would like to keep them sorted by the 1st element in the long[] ...(in this case, 10, 7 and 3). Is vector the right type of data structure to use for this? Basically, I am trying to keep them in some order, so that i can have a fast search on them when the index is unknown. Any suggestions??
    thanks

    First, don't use Vector.
    Declare your variables to be of type List, and then instantiate ArrayList (the direct replacement for Vector) or LinkedList, or whatever other custom List implementation suits your need.
    To maintain sort oder as objects are added, you can us a SortedSet (I think TreeSet is the implementation provided with the core APIs, but check the docs). However, this will be a Set, so if you need to add the same element more than once, you won't be able to use this.
    If you need it sorted and need to be able to have the "same" element (by equals()) multiple times, then either roll your own List implementation, or sacrifice maintaining order as elements are added and just explicitly call Collections.sort() when you need to sort it.

  • Finder sorting help?

    Hi, I want my finder Organized by 'Type' and sorted by 'Name', but every time I open a new folder I have to manually reset the sorting option, how can I set it by default so that every new windows I open is sorted that way?

    Hi Filippo1,
    If you are interested in setting a preferred Finder view, you may find the following article helpful:
    Mac OS X: How to Save a Finder View (Column, Icon, or List) for a Specific Folder or Disk
    http://support.apple.com/kb/TA20803
    Regards,
    - Brenden

  • Automator Sorting Help

    I'm trying to automate a particular function using Automator. I am hoping to take the entire contents of one folder and sort them to seperate folders of no more then 500MB each in total size. Each folder can be generically named as it is generated, but that max  total size of the folder is what's important. In looking at the selection list within Automator, I can't seem to figure out how to make this particular sort happen?
    Any help with this would be super appreciative.
    Thanks again.

    j. patrick wrote:
    I cannot get the subject line part to work. I drag the variable to the subject line and it adds a whole new process undernieth.
    Can you post a screen shot of the workflow?

  • Vector sorting in given order

    Lets say i have something like this
    A[]=[z,y,z,x,z,w,x,z,x,w,y];
    I would like to get in the given order
    like
    A[]=[z,z,z,z,w,w,w,x,x,x,x,y,y,y,y]
    If you see what i am saying....i want sorting in given order...i am using vector....
    Finding the way to appreciate your solution....
    thx
    Su

    Cross posted http://forum.java.sun.com/thread.jspa?threadID=753115

  • Vector sorting

    i save data on vector :
    while (st.hasMoreTokens())
              searchWord=st.nextToken();
         vector.addElement(searchWord);     
    vector={a,y,h,k,...,}
    then i calculate the occuerency of each words and save them in the second vector
    v2={1,9,2,5}
    i want to sort the 2 vector based on v2 " the number of occuerency for each word the result should be like :
    v1={y,k,h,a}
    v2={9,5,2,1}
    i did try to use for loop but unfortunately string.equals() or compareTo()doesn't work although i convert object to string
    any suggestions
    thanks

    Storing occurence and word in two diferent vectors (!) is yucky to begin with.
    Have an Occurance class. Make it implement Comparable using the counter variable. Then use Collections.sort() to sort the list of Occurence objects.

Maybe you are looking for