Compare element in a vector

hi,
I want to compare the float no in a vector e.g. [{0.2},{0.55}];
but I cannot just compare the 2 using x.elementAt(i) becoz this return object so
i do ix.elementAt(i) nstanceOf float but it pops up error,
but I am actually doing object instance of float, I am wondering where it was wrong
for(int i=1;i<x.size(); i++){
if(x.elementAt(i) instanceOf float){
if( x.elementAt(i)< x.elementAt(i-1)){
mean_dist.addElement(x.elementAt(i));
mean_dist.toString();
System.out.println("train data: "+ mean_dist);
anyone can give me idea
many thx

yep, sure thing, when you use Vector.elementAt(index) it returns an Object, not a Float
but... you KNOW its a Float cos thats what you put there! ok?
Vector has to return Object as when the class was written there was no idea what you would use it for and Object is the general class that coveres just about everything..
what you need to do is "cast" to Float, that is saying,
"ok you dont know its a Float, but I do ( I hope) and I want you to deal with it as a Float"
the way you do this is Float gimme=(Float)myVector.elementAt(index);this tell the compiler that you expect a Float and should deal with the return as a Float
the compiler will do its best to use what it gets as a Float, but if it cant (ie if you put something that isnt a Float in myVector at (index)) then it will generate a ClassCastException
you dont HAVE to catch this, but you may if you want

Similar Messages

  • Comparing elements inside a vector

    Hello,
    I am having a hard time understanding how to compare elements inside a vector. I have a vector of six strings and I want to compare the first element at index 0 with all other elements at positions 1-5. After that, compare the element at position 1 with elements at positions 2-5 and so on until all elements have been compared against each other.
    Can some one please advise me on how to achieve this?
    Thank you.

    joor_empire wrote:
    Thanks for replying. I tried using nested loops, but I keep getting array index out of bound error.Hmmm, then you're doing it wrong.
    For more information, you'll have to give us more info, such as your code (please use code tags when posting it though).

  • Comparing elements in vector..

    hi ,
    how to compare elements in 2 vectors(diff size)
    pls help
    arvin

    thks for your help,
    for(int i=0;i<=v.size();i++)
    if(v.elementAt(i).equals(v2.elementAt(i))
    }when i did like this iam getting error
    arvin

  • Can not find individual element in the Vector

    Hi everyone,
    I have employeeRecord class .
    I have employee Vector.
    I have created two employeeRecord and added them to my employee Vector.
    I am trying to test my employee Vector by using lgName = "rez704" .
    However I do not see any result.
    I was expecting the for loop to go through my employee Vector and
    find the login name which matches with my test variable lgName.
    ANy clues?
    many thanks
    Vector  employeeVector = new Vector();
    Enumeration e = empVector.elements();
      String nameLog = "rea700";
      String fName   = "ameri";
      String passW   = "765";
      employeeRecord  emp = new employeeRecord(nameLog, fName, passW);
      empolyeeVector.addElement(emp);
      String nameLog2 = "rez704";
      String fName2   = "Xamre";
      String passW2   = "kv281"
      employeeRecord  emp = new employeeRecord(nameLog2, fName2, passW2);
      empolyeeVector.addElement(emp);
      String lgName = "rez704";
      int i = 0;
      for(Enumeration e1 = employeeVector.elements() ; e1.hasMoreElements() ;)
                if (lgName.equals(empVector.elementAt(i)))
                   System.out.println("Login Name Found");
             e1.nextElement();
          }

    Hi everyone,
    I have employeeRecord class .
    I have employee Vector.
    I have created two employeeRecord and added them to
    my employee Vector.
    I am trying to test my employee Vector by using
    lgName = "rez704" .
    However I do not see any result.
    I was expecting the for loop to go through my
    employee Vector and
    find the login name which matches with my test
    variable lgName.
    ANy clues?
    many thanks
    Vector  employeeVector = new Vector();
    Enumeration e = empVector.elements();
    String nameLog = "rea700";
    String fName   = "ameri";
    String passW   = "765";
    employeeRecord  emp = new employeeRecord(nameLog,
    g, fName, passW);
    empolyeeVector.addElement(emp);
    String nameLog2 = "rez704";
    String fName2   = "Xamre";
    String passW2   = "kv281"
    employeeRecord  emp = new employeeRecord(nameLog2,
    2, fName2, passW2);
    empolyeeVector.addElement(emp);
    String lgName = "rez704";
    int i = 0;
    for(Enumeration e1 = employeeVector.elements() ;
    ; e1.hasMoreElements() ;)
    if
    if (lgName.equals(empVector.elementAt(i)))
    System.out.println("Login Name
    tln("Login Name Found");
    e1.nextElement();
    Hi Guys,
    No, none of the solution works!!
    I tired the following just for testing.
    int l = 0;
    if ( empVector.elementAt(l).equals(e1.nextElement()) )
    <
    <
    <
    it only prints the first employee record
    Login Name Found
    login Name = reza700
    Last name = ameri
    passWord = 765
    in my original question which I had posted, I wanted to compare not the whole Vector object but
    only to access loginName whithin the emplyoeeVector and comapare it
    with the lgName which is used as testing.
    But the example which I had uesed above and it the wrong type of example the wole emplyoee record is found in the emplyoee vector.
    any help is appreciated.
    thank you again

  • Sorting a vector where each element is a vector

    Hi,
    Sorry for the post but I can't seem to get my head around sorting in Java using Comparator.
    I've a vector where each element is a vector containing strings, integers and doubles and the first element of each vector is a double.
    I need to sort the vector based on this first value of each element which is a vector.
    Hope some can help,
    Thanks in advance,
    Lou

    Here is a generic comparator you can use to sort a List. Vector implements the List interface to you can sort the Vector.
    import java.util.Comparator;
    import java.util.List;
    * A comparator to sort Lists of data based on a column within each List
    public class ListComparator implements Comparator
        private int column;
        private boolean ascending;
        ListComparator(int column, boolean ascending)
            this.column = column;
            this.ascending = ascending;
        public int compare(Object a, Object b)
            List v1 = (List)a;
            List v2 = (List)b;
            Object o1 = v1.get(column);
            Object o2 = v2.get(column);
            // Treat empty strings 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;
            if (o1 == null) return 1;
            if (o2 == null) return -1;
            //  Compare objects
            if (o1 instanceof Comparable)
                if (ascending)
                    return ((Comparable)o1).compareTo(o2);
                else
                    return ((Comparable)o2).compareTo(o1);
            else  // Compare as a String
                if (ascending)
                    return o1.toString().compareTo(o2.toString());
                else
                     return o2.toString().compareTo(o1.toString());
    }You invoke the sort by using:
    Collections.sort(yourVector, new ListComparator(column, ascending));

  • How to associate lines in a text file as an elements of the Vector?

    Hi!
    I have used BufferedReader(new FileReader(c:/java/MyText.txt)) to read from MyText.txt file. Now I know how to load content of this file (every line in file describes each photo in my photo-set) into a Vector. But how to associate lines of MyText.txt as an elements of the Vector?
    Thanks Felipe for his help.
    DM.

    Thank you telism,
    Let me tell you the whole story.
    I'm trying to write an application which has to show my image files (set of photos) with a text description. The list of image files placed into the JList. So, when I select a file from the JList it shows me an image (everything is OK).
    But, every image has it's text description in MyText.text file. It's a file with each text line for every image. Actually, I am trying to connect two actions - showing my image and setting it's specified text line description (from MyText.txt) in a JTextArea. I thought that the best way to do this with my text it is like I did it with my images through Vector. But No Success.
    Can You help me on that? If You will show me how to do it on my example I will really appreciate it.
    Thank You DM.
    Here is my application:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class UnitA extends JPanel implements ListSelectionListener {
    BasicUnitA Myapplet;
    JPanel listPanel, picturePanel;
    Vector imageNames1;
    JList list1;
    JLabel picture1;
    JScrollPane listScrollPane1, pictureScrollPane1, TSP1;
    JTextArea TA1;
    int index;
    UnitA (BasicUnitA parent, boolean p1, boolean p2) {
    Myapplet=parent;
    //Read image names from a properties file
    ResourceBundle imageResource1;
    try{
    imageResource1 = ResourceBundle.getBundle("imagenames1");
    String imageNamesString1 = imageResource1.getString("images");
    imageNames1 = parseList(imageNamesString1);
    } catch (MissingResourceException e) {
    System.err.println("Please, add properties file with image names.");
    System.exit(1);
    //Create one list of images and put it in a scroll pane and panel
    list1 = new JList(imageNames1);
    list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list1.setSelectedIndex(0);
    list1.addListSelectionListener(this);
    listScrollPane1 = new JScrollPane(list1);
    listScrollPane1.setPreferredSize(new Dimension (120,120));
    //Set up the picture label and put it in a scroll pane
    ImageIcon firstImage1 = new ImageIcon("java/Applications/images/fotos/" +
    (String)imageNames1.firstElement());
    picture1 = new JLabel(firstImage1);
    picture1.setPreferredSize(new Dimension (firstImage1.getIconWidth(),
    firstImage1.getIconHeight()));
    pictureScrollPane1 = new JScrollPane(picture1);
    pictureScrollPane1.setPreferredSize(new Dimension (500,360));
    pictureScrollPane1.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createCompoundBorder(
    BorderFactory.createLoweredBevelBorder(),
    BorderFactory.createEmptyBorder(5,5,5,5)),
    BorderFactory.createLineBorder(Color.black)));
    pictureScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLL
    BAR_ALWAYS);
    TA1 = new JTextArea();
    TA1.setLineWrap(true);
    TA1.setWrapStyleWord(true);
    TA1.setEditable(false);
    TA1.setFont(new Font("Serif", Font.PLAIN, 16));
    TSP1 = new JScrollPane(TA1);
    TSP1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_
    ALWAYS);
    TSP1.setPreferredSize(new Dimension(500,40));
    TSP1.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createCompoundBorder(
    BorderFactory.createLoweredBevelBorder(),
    BorderFactory.createEmptyBorder(5,5,5,5)),
    BorderFactory.createLineBorder(Color.black)));
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    JList theList1 = (JList)e.getSource();
    if (theList1.isSelectionEmpty()) {
    picture1.setIcon(null);
    TA1.setText(null);
    } else {
    index = theList1.getSelectedIndex();
    ImageIcon newImage1 = new
    ImageIcon("java/Applications/images/fotos/" +
    (String)imageNames1.elementAt(index));
    picture1.setIcon(newImage1);
    picture1.setPreferredSize(new Dimension (newImage1.getIconWidth(),
    newImage1.getIconHeight()));
    picture1.revalidate();
    try{
    BufferedReader reader = new
    BufferedReader(new FileReader("c:/java/Applications/MyText.txt")));
    String str;
    while((str = reader.readLine()) != null) {
    TA1.setText(TA1.getText()+str);
    reader.close();
    }catch(IOException evt){};
    protected static Vector parseList(String theStringList) {
    Vector v = new Vector(10);
    StringTokenizer tokenizer = new StringTokenizer (theStringList, " ");
    while (tokenizer.hasMoreTokens()) {
    String image = tokenizer.nextToken();
    v.addElement(image);
    return v;

  • Which interface would you use to list each element of a vector?

    Which interface would you use to list each element of a vector?

    The laugh's on you, twit! Nobody takes kindly to lazy bums trying to cheat on their homework nor exams. Take a hike loser!

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

  • Display elements inside a vector

    How do I display the elements inside a vector and place it inside a TextArea in a JFrame?
    //start of Itm class
    public class Itm
         private String name;
         private int qty;
         private double price;
         public int SetQty (int nQty)
              qty = 0;
              if (nQty>0)
                   qty = nQty ;
              return qty;
         public String SetName (String strName)
              name = "";
              name = strName;
              return name;
         public double SetPrice (String name)
              if (name == "6pcs. Chckn McNggts")
                   price = 57;
              else if (name == "HB")
                   price = 25;
              else if (name == "Big Mac Meal")
                   price = 115;
              else if (name == "CHB Meal")
                   price = 115;
              else if (name == "RICE")
                   price = 11;
              else if (name == "1pc. Chicken Mcdo w/rice")
                   price = 57;
              else if (name == "CHB")
                   price = 35;
              else if (name == "1pc. Chicken w/Sphtti")
                   price = 90;
              else if (name == "BMD Meal")
                   price = 50;
              else if (name == "GRAVY")
                   price = 8;
              else if (name == "Mc Spghtti")
                   price = 35;
              else if (name == "DCHB")
                   price = 69;
              else if (name == "1pc. Chickn Mcdo Happy Ml")
                   price = 92;
              else if (name == "Mc Spghtti Happy Ml")
                   price = 76;
              else if (name == "X-SAUCE")
                   price = 8;
              else if (name == "Mc Rice Brgr Beef Sprme")
                   price = 75;
              else if (name == "Qrtr Pounder w/cheese")
                   price = 85;
              else if (name == "Mc Flurry")
                   price = 30;
              else if (name == "Sundae Cup")
                   price = 25;
              else if (name == "X-MAYO")
                   price = 8;
              else if (name == "Mc Rice Brgr Chckn Sprme")
                   price = 85;
              else if (name == "Big Mac")
                   price = 85;
              else if (name == "PIE")
                   price = 20;
              else if (name == "Sundae Cone - Vanilla")
                   price = 12;
              else if (name == "ICE MIX")
                   price = 25;
              else if (name == "Crispy Chicken Fillet")
                   price = 35;
              else if (name == "Reg Fries")
                   price = 25;
              else if (name == "Mc Float")
                   price = 25;
              else if (name == "Mc Float w/LFries")
                   price = 55;
              else if (name == "Ornge Juice")
                   price = 26;
              else if (name == "Brgr Mcdo")
                   price = 25;
              else if (name == "Lrge Fries")
                   price = 36;
              else if (name == "Softdrink")
                   price = 19;
              else if (name == "Icd Tea")
                   price = 26;
              else if (name == "Coffee")
                   price = 27;
              return price;
    //end of Itm class
    //start of Receipt class
    import java.util.*;
    public class Receipt
         Vector vReceipt = new Vector();
         Itm i = new Itm();
         public void addItem (Itm i)
              vReceipt.addElement(i);
    //end of Receipt class

    http://forum.java.sun.com/thread.jspa?threadID=5225026&tstart=0
    Thanks for double posting butthole!
    NO HELP FOR YOU

  • HOW TO DELETE DUPLICATE ELEMENT IN A VECTOR

    Hi everybody!
    If I've a vector like this vectA={apple,orange,grape,apple,apple,banana}
    and I want final result be vectB={apple,orange,grape,banana}.
    How should I compare each element in vectA and delete duplicate element. Like here duplicated element is apple. Only one apple remain in the vectB.
    Any help,
    Thanks.

    Hello all. Good question and good answers, but I would like to elaborate.
    To begin with, you specifically asked to map the following:
    {apple,orange,grape,apple,apple,banana} ==> {apple,orange,grape,banana}
    Both of cotton.m's solutions do NOT do this, unfortunately. They are both useful in particular cases though, so think about what you're trying to do:
    cotton.m's first solution is best if order does not matter. In fact, as flounder first stated, whenever order doesn't matter, your most efficient bet is to use a Set instead of a List (or Vector) anyways.
    Set vectB = new HashSet(vectA);This code maps to {banana, orange, grape, apple}, because HashSets are "randomly" ordered.
    cotton.m's second solution is good if you want to impose NEW ordering on the List.
    Set vectB = new TreeSet(vectA);This code maps to {apple, banana, grape, orange}, because TreeSet uses alphabetical-order on Strings by default.
    java_2006, your solution is the most correct, but it's a little verbose for my taste :)
    more importantly, the runtime-efficiency is pretty bad (n-squared). calling Vector.contains performs (at worst) n comparisons; you're going to call it n times! Set.contains usually performs 2 comparisons (constant, much better), so I suggest you USE a Set to do the filtering, while still sticking with your good idea to use a List. When the ordering is "arbitrary" (so can't use TreeSet) but still relevant (so can't use HashSet), you're basically talking about a List.
    I think saving A LOT of time is worth using A LITTLE extra space, so here, let's save ourself some runtime, and some carpal-tunnel.
    import java.util.*;
    class Foo {
         public static void main(String[] args) {
              String[] fruits = {"apple","orange","grape","apple","apple","banana"};
              List     l = Arrays.asList(fruits),
                   m = filterDups(l);
              System.out.println(m);
         // remember, both of the following methods use O(n) space, but only O(n) time
         static List filterDups(List l) {
              List retVal = new ArrayList();
              Set s = new HashSet();
              for (Object o : l)
                   if (s.add(o))
                        retVal.add(o);     // Set.add returns true iff the item was NOT already present
              return retVal;
         static void killDups(List l) {
              Set s = new HashSet();
              for (Iterator i = l.iterator(); i.hasNext(); )
                   if (! s.add(i.next()))     
                        i.remove();
         // honestly, please don't use Vectors ever again... thanks!
         // if you're going to be a jerk about it, and claim you NEED a Vector result
         // then here's your code, whiner
         public static void mainx(String[] args) {
              String[] fruits = {"apple","orange","grape","apple","apple","banana"};
              List l = Arrays.asList(fruits);
              Vector v = new Vector(l);
              killDups(v);
              System.out.println(v);
    }

  • How to search and delete repeated elements in a vector

    Hi again,
    In a class of my application, it needs to check in a vector (A), if there are repeated elements, if it founds one, then it is replaced for a *. then the elements different from * are copied into a new vector(Aa). the code is the following:
    //here are defined the components Textfield, etc
    public void Bconj_Action(Object target)
              int idx = 0;
              int tokenCount;
              String var="";
              String var2="";
              String A[] = new String [50];
              String Aa[] = new String [50];
              String message = (TxtA.getText());
              StringTokenizer st = new StringTokenizer(message,",");
              tokenCount = st.countTokens();
              while (st.hasMoreTokens())
                   A[idx] = st.nextToken();
                   idx++;
              //Recorre vector A en busca de repetidos     
              for(int n=0;n<tokenCount-1;n++)
              for(int m=n+1;m<tokenCount;m++)
              if (A[m]==A[n] && A[n]!="*")
                   A[n]="*";
              //Recorre nuevamente el vector A buscando los diferente a * que seran copiados al vector Aa
              int o = 0;
              for (int n=1;n<tokenCount;n++)
              if(A[n]!="*")
              Aa[o]=A[n];
                   o++;
              for (int i=0;i<tokenCount; i++)
                        if (i==0){
                        var=Aa;}
                                  else{
                                  var = var + "," + Aa[i];}
                   TxtA.setText("");
                   TxtU.setText(var);
    when I run it, and I enter to the prog 1, it don't show me nothing, when I enter 1,1 it shows me 1,null and so on.
    do you have any ideas of what is happening.
    Thanks in advance.

    Two things I would point out to you:
    Its possible that the way you are comparing the Strings is causing a problem for you.
    if (A[m]==A[n] && A[n]!="*")
    A[n]="*";
    }A[m] and A[n] are two Strings so you should compare them using
    A[m].equals(A[n]).So the if statement should look like this:
    if (A[m].equals(A[n]) && !A[n].equals("*"))
    A[n]="*";
    }And second:
    When you copy the unique elements over to array Aa you may be copying less that tokenCount elements. You are actually copying o elements.
    The final for loop could be modified like this:
    for (int i=0;i<o; i++)
    if (i==0){
    var=Aa;}
    else{
    var = var + "," + Aa[i];}
    TxtA.setText("");
    TxtU.setText(var);
    } Thus it prints only the unique elements found rather than the whole array which may contain nulls.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can I sort on the second element of my vector?

    Sorry to intrude on the guru territory, but no one in the newbie camp has answered and I am sure someone over here has a quick answer...
    The first element is first name and the second is lastname. Right now I am using java.util.Collections.sort(v); This searches on the first name. I would like to search on the last name which is the second element. Any ideas?

    I'm not sure what's in your vector. I assume the vector contains strings, of the form "firstname lastname". In which case I suspect the default implemetation of sort is simply sorting the strings in the natural way. If you look at the second implementation of sort():
    sort(List l, Comparator c)
    you can implement your own comparator. The comparator is an interface tast you implement to compare two object the way you want th sorting done.
    so your comparator would implement compare to find the second word of each string (look at string tokenizer for this) and compare them (with String.compareTo). You need to do something similar with equals.
    So you call sort like this: sort(myVector,new MyComparator());
    Hope this helps.

  • URGENT: Removing element from a vector?

    ok I have a text database where the lines look something like this:
    5876,Tigger,50.00
    7892,Piglet,25.00
    my problem is I have to remove an element that I don't know the index of, so I figured I have to search the vector for the number(eg, 5876) and return the index so I can remove it, but I don't know how to do this. Please help me

    Try this:
    public class Parser
    public Vector read(InputStream in) throws IOException
       Vector structures = new Vector();
       StringBuffer buffer = new StringBuffer(128);
       int n = -1;
       while((n = in.read()) != -1)
          char c = (char)n;
          if(c == '\n')
             structures.add(getDataStructure(buffer.toString()));
             buffer.delete(0, buffer.length());
          } else
             buffer.append(c);
       if(buffer.length() > 0)
          structures.add(getDataStructure(buffer.toString()));
       return structures;
    protected DataStructure getDataStructure(String string)
       DataStructure structure = new DataStructure();
       StringTokenizer st = new StringTokenizer(string, String.valueOf(','));
       structure.id = (String)st.nextElement();
       structure.name = (String)st.nextElement();
       structure.price = Float.parseFloat((String)st.nextElement());
       return structure;
    public class DataStructure
       String id;
       String name;
       float price;
       public DataStructure() {}
       public boolean equals(Object o)
          if(o instanceof DataStructure)
             return id.equals(((DataStructure)o).id);
          } else if(o instanceof String)
             return id.equals((String)id);
          return false;
    }Now you can keep track of the info in a better way.
    If you have
    5876,Tigger,50.00
    5876,Tigger,50.00
    5876,Tigger,50.00
    5876,Tigger,50.00
    5876,Tigger,50.00
    Stored in a file, you can do this:
    Vector v = new Parser().read(new FileInputStream("..."));
    Structure s = (Structure)v.elementAt(0);
    System.out.println(s.name);
    v.remove("5876");Isn't that nice?
    Note that the code may or may not compile.
    Hope it helps,
    Nille

  • Comparing elements in 2d array

    Hi all
    I need a solution. The problem is I have a 2-d array of numbers. I have to display a array subset such that the elements in the first row fall in the ranges provided by me through user prompt.  

    04998285626 wrote: 
    ...The problem is I have a 2-d array of numbers. I have to display a array subset such that the elements in the first row fall in the ranges provided by me through user prompt.  
    And...
    04998285626 wrote:
    its like i have a 2d array of numbers in increasing order. i input a number and i have to get the output array as all the elements that are less than it in the same order.( or rather get a subarray upon comparing the elements )
    OK, let's try to interpret this once more in clearer language. Apparently, the first row has some significance.
    Maybe only the first row is increasing in value and we want to keep the subset of the 2D containing all columns that are below a threshold in the first element. Since the values in the first row are increasing, all we need to do is find the column index where the first element is too big, and then take the subset of the 2D array up to this point. Here is a solution for this interpretation of the task.
    You still might need to adjust for detail, e.g. use "greater or equal?" instead of "greater?" depending on your exact needs.
    Message Edited by altenbach on 08-23-2008 11:19 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Trim2DArray.png ‏28 KB

  • Can I sort by the second element in my vector?

    The first element is first name and the second is lastname. Right now I am using java.util.Collections.sort(v); This searches on the first name. I would like to search on the last name which is the second element. Any ideas?

    Write a subclass of Comparator that looks at the second element, and give an instance of it to the sort method along with the array.

Maybe you are looking for