Storing Coordinates as integers in a Vector or ArrayList??

Greetings all,
I am trying to store a set of (x,y) coordinates in either a vector or an arraylist but don't really know which one is better or really the proper way to be doing it ... from my understanding firstly these numbers are stored as objects rather than integers, but i need them as integers because i would like to plug them into equations etc., from my understanding of vectors the code is something like this:
Vector v = new Vector();
v.addElement(0);
v.addElement(1);
v.addElement(2);
v.addElement(3);which results in a vector like v=[0,1,2,3] which if i'm not mistaken are objects not integers, but what if i want a vector which stores numbers as v=[(0,0), (1,0), (2,0), (3,0)] that are integers?
Your help is much appreciated.
Thanks.

Take the collections tutorial: [http://java.sun.com/docs/books/tutorial/collections/index.html]
Prefer collections framework classes like ArrayList over older legacy classes like Vector.
demo:
import java.awt.Point;
import java.util.*;
public class ListExample {
    public static void main(String[] args) {
        List<Point> points = new ArrayList<Point>();
        points.add(new Point(1,2));
        points.add(new Point(5,3));
        System.out.println(points);
}

Similar Messages

  • Vector or ArrayList  use for dropdown with more than 1000 entries

    Hi Friends
    I am having more than 1000 entries of different TimeZone's which i need to display in a dropdown list.
    i am not able to decide whether i need to use a Vector or Arraylist for storing these values.
    please let me know which one will be best suited to use in case the list entry is more than 1000 characters.
    waiting for a positive reply from your side.
    Thanks & Regards
    Vikeng

    A JComboBox can be constructed from a Vector (rather than any other sort of List) without having to implement your own ComboBoxModel. (JList is similar).
    I agree with kajbj - a control like this with a thousand entries is rather poor interface design. One exception might be if the entries are sorted in some way, and you "jump" to the appropriate place in the list as the user types.

  • Need help in storing data from JList into a vector

    need help in doing the following.-
    alright i click a skill on industryskills Jlist and press the add button and it'll be added to the applicantskills Jlist. how do i further store this data that i added onto the applicantskills JList into a vector.
    here are the codes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
    import java.util.Vector;
    import javax.swing.JScrollPane.*;
    //import javax.swing.event.ListSelectionListener;
    public class Employment extends JFrame
            //declare class variables
            private JPanel jpApplicant, jpEverything,jpWEST, jpCENTRE, jpEAST, jpAddEditDelete,
                                       jpCentreTOP, jpCentreBOT, jpEastTOP, jpEastCENTRE, jpEastBOT,
                                       jpBlank1, panel1, panel2, panel3, panel4,jpBottomArea,
                                       jpEmptyPanelForDisplayPurposes;
            private JLabel jlblApplicantForm, jlblAppList, jlblName, jlblPhone,
                                       jlblCurrentSalary, jlblPassword, jlblDesiredSalary,
                                       jlblNotes, jlblApplicantSkills, jlblIndustrySkills,
                                       jlblBlank1, jlblBlank2, ApplicantListLabel,
                                       NotesListLabel, ApplicantSkillsLabel,
                                       IndustrySkillsLabel,jlblEmptyLabelForDisplayPurposes;  
            private JButton jbtnAdd1, jbtnEdit, jbtnDelete, jbtnSave, jbtnCancel,
                                            jbtnAdd2, jbtnRemove;
            private JTextField jtfName, jtfPhone, jtfCurrentSalary, jtfPassword,
                                               jtfDesiredSalary;
              private JTabbedPane tabbedPane;
            private DefaultListModel /*listModel,*/listModel2;
              String name,password,phone,currentsalary,desiredsalary,textareastuff,NotesText;
              String selectedname;
            final JTextArea Noteslist= new JTextArea();;
            DefaultListModel listModel = new DefaultListModel();
            JList ApplicantSkillsList = new JList(listModel);
           private ListSelectionModel listSelectionModel;
            JList ApplicantList, /*ApplicantSkillsList,*/ IndustrySkillsList;
            //protected JTextArea NotesList;    
                    //Vector details = new Vector();
                  Vector<StoringData> details = new Vector<StoringData>();             
                public static void main(String []args)
                    Employment f = new Employment();
                    f.setVisible(true);
                    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    f.setResizable(false);
                }//end of main
                    public Employment()
                            setSize(800,470);
                            setTitle("E-commerce Placement Agency");
                                  Font listfonts = new Font("TimesRoman", Font.BOLD, 12);
                            JPanel topPanel = new JPanel();
                            topPanel.setLayout( new BorderLayout() );
                            getContentPane().add( topPanel );
                            createPage1();
                            createPage2();
                            createPage3();
                            createPage4();
                            tabbedPane = new JTabbedPane();
                            tabbedPane.addTab( "Applicant", panel1 );
                            tabbedPane.addTab( "Job Order", panel2 );
                            tabbedPane.addTab( "Skill", panel3 );
                            tabbedPane.addTab( "Company", panel4 );
                            topPanel.add( tabbedPane, BorderLayout.CENTER );
            public void createPage1()//PAGE 1
                 /*******************TOP PART********************/
                            panel1 = new JPanel();
                            panel1.setLayout( new BorderLayout());
                                  jpBottomArea = new JPanel();
                                  jpBottomArea.setLayout(new BorderLayout());
                            jpApplicant= new JPanel();
                            jpApplicant.setLayout(new BorderLayout());
                            Font bigFont = new Font("TimesRoman", Font.BOLD,24);
                            jpApplicant.setBackground(Color.lightGray);
                            jlblApplicantForm = new JLabel("\t\t\t\tAPPLICANT FORM  ");
                            jlblApplicantForm.setFont(bigFont);
                            jpApplicant.add(jlblApplicantForm,BorderLayout.EAST);
                            panel1.add(jpApplicant,BorderLayout.NORTH);
                            panel1.add(jpBottomArea,BorderLayout.CENTER);
           /********************************EMPTY PANEL FOR DISPLAY PURPOSES*************************/
                               jpEmptyPanelForDisplayPurposes = new JPanel();
                               jlblEmptyLabelForDisplayPurposes = new JLabel(" ");
                               jpEmptyPanelForDisplayPurposes.add(jlblEmptyLabelForDisplayPurposes);
                               jpBottomArea.add(jpEmptyPanelForDisplayPurposes,BorderLayout.NORTH);
           /*****************************************WEST*********************************/             
                            jpWEST = new JPanel();                 
                            jpWEST.setLayout( new BorderLayout());
                            //Applicant List
                                  listModel2=new DefaultListModel();
                                  ApplicantList = new JList(listModel2);
                                listSelectionModel = ApplicantList.getSelectionModel();
                                listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
                                JScrollPane scrollPane3 = new JScrollPane(ApplicantList);
                                  ApplicantList.setPreferredSize(new Dimension(20,40));
                                 scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);                                             
                                scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            ApplicantListLabel = new JLabel( "Applicant List:");
                            jpWEST.add(ApplicantListLabel,"North"); 
                            jpWEST.add(scrollPane3,"Center");
                            jpBottomArea.add(jpWEST,BorderLayout.WEST);
                            /*********CENTRE*********/
                            jpCENTRE = new JPanel();
                            jpCENTRE.setLayout(new GridLayout(2,1));
                            jpCentreTOP = new JPanel();
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            jpCENTRE.add(jpCentreTOP);
                            jpCentreTOP.setLayout(new GridLayout(6,2));
                              //Creating labels and textfields
                            jlblName = new JLabel( "Name:");
                            jlblBlank1 = new JLabel ("");
                            jtfName = new JTextField(18);
                            jlblBlank2 = new JLabel("");
                            jlblPhone = new JLabel("Phone:");
                            jlblCurrentSalary = new JLabel("Current Salary:");
                            jtfPhone = new JTextField(13);
                            jtfCurrentSalary = new JTextField(7);
                            jlblPassword = new JLabel("Password:");
                            jlblDesiredSalary = new JLabel("Desired Salary:");
                            jtfPassword = new JTextField(13);
                            jtfDesiredSalary = new JTextField(6);
                              //Add labels and textfields to panel
                            jpCentreTOP.add(jlblName);
                            jpCentreTOP.add(jlblBlank1);
                            jpCentreTOP.add(jtfName);
                            jpCentreTOP.add(jlblBlank2);
                            jpCentreTOP.add(jlblPhone);
                            jpCentreTOP.add(jlblCurrentSalary);
                            jpCentreTOP.add(jtfPhone);
                            jpCentreTOP.add(jtfCurrentSalary);
                            jpCentreTOP.add(jlblPassword);
                            jpCentreTOP.add(jlblDesiredSalary);
                            jpCentreTOP.add(jtfPassword);
                            jpCentreTOP.add(jtfDesiredSalary);
                            //Noteslist
                            jpCentreBOT = new JPanel();
                            jpCentreBOT.setLayout( new BorderLayout());
                            jpCENTRE.add(jpCentreBOT);
                            jpBlank1 = new JPanel();
                             //     Noteslist = new JTextArea(/*Document doc*/);
                            JScrollPane scroll3=new JScrollPane(Noteslist);
                                scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                                scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            NotesListLabel = new JLabel( "Notes:");
                            jpCentreBOT.add(NotesListLabel,"North"); 
                            jpCentreBOT.add(scroll3,"Center");
                            jpCentreBOT.add(jpBlank1,"South");
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            /**********EAST**********/
                            //Applicant Skills Panel
                            //EAST ==> TOP
                            jpEAST = new JPanel();
                            jpEAST.setLayout( new BorderLayout());
                            jpEastTOP = new JPanel();
                            jpEastTOP.setLayout( new BorderLayout());
                            ApplicantSkillsLabel = new JLabel( "Applicant Skills");
                            JScrollPane scrollPane1 = new JScrollPane(ApplicantSkillsList);
                               scrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                              scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);                                             
                            ApplicantSkillsList.setVisibleRowCount(6);
                            jpEastTOP.add(ApplicantSkillsLabel,"North"); 
                            jpEastTOP.add(scrollPane1,"Center");
                            jpEAST.add(jpEastTOP,BorderLayout.NORTH);
                            jpBottomArea.add(jpEAST,BorderLayout.EAST);
                            //Add & Remove Buttons
                            //EAST ==> CENTRE
                            jpEastCENTRE = new JPanel();
                            jpEAST.add(jpEastCENTRE,BorderLayout.CENTER);
                            jbtnAdd2 = new JButton("Add");
                            jbtnRemove = new JButton("Remove");
                            //add buttons to panel
                            jpEastCENTRE.add(jbtnAdd2);
                            jpEastCENTRE.add(jbtnRemove);
                            //add listener to button
                           jbtnAdd2.addActionListener(new Add2Listener());
                           jbtnRemove.addActionListener(new RemoveListener());
                            //Industry Skills Panel
                            //EAST ==> BOTTOM
                            jpEastBOT = new JPanel();
                            jpEastBOT.setLayout( new BorderLayout());
                           String[] data = {"Access97", "Basic Programming",
                           "C++ Programming", "COBOL Programming",
                           "DB Design", "Fortran programming"};
                           IndustrySkillsList = new JList(data);
                           JScrollPane scrollPane = new JScrollPane(IndustrySkillsList);
                           scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                           scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                           IndustrySkillsLabel = new JLabel( "Industry Skills:");
                           jpEastBOT.add(IndustrySkillsLabel,"North"); 
                           jpEastBOT.add(scrollPane,"Center");
                           jpEAST.add(jpEastBOT,BorderLayout.SOUTH);
                            //BOTTOM
                            jpAddEditDelete= new JPanel();
                            jbtnAdd1=       new JButton("Add");
                            jbtnEdit=       new JButton("Edit");
                            jbtnDelete=     new JButton("Delete");
                            jbtnSave=       new JButton("Save");
                            jbtnCancel=     new JButton("Cancel");
                            jpAddEditDelete.add(jbtnAdd1);
                            jpAddEditDelete.add(jbtnEdit);
                            jpAddEditDelete.add(jbtnDelete);
                            jpAddEditDelete.add(jbtnSave);
                            jpAddEditDelete.add(jbtnCancel);
                               jbtnEdit.addActionListener(new EditListener());
                               jbtnDelete.addActionListener(new DeleteListener());
                                jbtnEdit.addActionListener(new EditListener());
                            jbtnAdd1.addActionListener(new Add1Listener());
                            jbtnCancel.addActionListener(new CancelListener());
                            jpBottomArea.add(jpAddEditDelete,BorderLayout.SOUTH);
            public void createPage2()//PAGE 2
                    panel2 = new JPanel();
                    panel2.setLayout( new GridLayout(1,1) );
                    panel2.add( new JLabel( "Sorry,under construction" ) );
            public void createPage3()//PAGE 3
                    panel3 = new JPanel();
                    panel3.setLayout( new GridLayout( 1, 1 ) );
                    panel3.add( new JLabel( "Sorry,under construction" ) );
            public void createPage4()//PAGE 4
                    panel4 = new JPanel();
                    panel4.setLayout( new GridLayout( 1, 1 ) );
                    panel4.add( new JLabel( "Sorry,under construction" ) );
            public class Add1Listener implements ActionListener
            public void actionPerformed(ActionEvent e)
                    name = jtfName.getText();
                    password = jtfPassword.getText();
                    phone = jtfPhone.getText();
                    currentsalary = jtfCurrentSalary.getText();
                    int i= Integer.parseInt(currentsalary);
                    desiredsalary = jtfDesiredSalary.getText();
                    int j= Integer.parseInt(desiredsalary);
                       StoringData person = new StoringData(name,password,phone,i,j);
                   //     StoringData AppSkillsList = new StoringData(listModel);
                    details.add(person);
                 //     details.add(AppSkillsList);
                  listModel2.addElement(name);
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");
    //                NotesList.setText("");
            public class Add2Listener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                           String temp1;
                           temp1 = (String)IndustrySkillsList.getSelectedValue();
                           listModel.addElement(temp1);
            public class RemoveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            int index = ApplicantSkillsList.getSelectedIndex();
                                listModel.remove(index);
            public class EditListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            jtfName.setEditable(true);
                            jtfPassword.setEditable(true);
                            jtfPhone.setEditable(true);
                            jtfCurrentSalary.setEditable(true);
                            jtfDesiredSalary.setEditable(true);
                            Noteslist.setEditable(true);
                            jbtnAdd2.setEnabled(true);               
                            jbtnRemove.setEnabled(true);
                            jbtnSave.setEnabled(true);
                            jbtnCancel.setEnabled(true);                     
            public class DeleteListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                        int index1 = ApplicantList.getSelectedIndex();
                            listModel2.remove(index1);
            public class SaveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
            public class CancelListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");                         
            public class SharedListSelectionHandler implements ListSelectionListener
            public void valueChanged(ListSelectionEvent e)
             selectedname =ApplicantList.getSelectedValue().toString();
             StoringData selectedPerson = null;
             jtfName.setEditable(false);
             jtfPassword.setEditable(false);
             jtfPhone.setEditable(false);
             jtfCurrentSalary.setEditable(false);
             jtfDesiredSalary.setEditable(false);                                 
             Noteslist.setEditable(false);
             jbtnAdd2.setEnabled(false);               
             jbtnRemove.setEnabled(false);
             jbtnSave.setEnabled(false);
             jbtnCancel.setEnabled(false);
                   for (StoringData person : details)
                          if (person.getName1().equals(selectedname))
                                 selectedPerson = person;
                                 jtfName.setText(person.getName1());
                                 jtfPassword.setText(person.getPassword1());
                              jtfPhone.setText(person.getPhone1());
                              //String sal1 = Integer.parseString(currentsalary);
                             // String sal2 = Integer.parseString(desiredsalary);
                             // jtfCurrentSalary.setText(sal1);
                             // jtfDesiredSalary.setText(sal2);
                                 break;
                   //     if (selectedPerson != null)
    }

    Quit posting 300 line programs to ask a question. We don't care about your entire application. We only care about code that demonstrates your current problem. We don't want to read through 300 lines to try and find the line of code that is causing the problem.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Here is a simple SSCCE. Now make your changes and if you still have problems you have something simple to post. If it works then you add it to your real application.
    Learn to simplify your problem by simplifying the code.
    import java.awt.*;
    import javax.swing.*;
    public class ListTest2 extends JFrame
         JList list;
         public ListTest2()
              String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
              list = new JList( numbers );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListTest2 frame = new ListTest2();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • How to storing more than 1 data to vector

    hi,
    I would like to know if I can store the following:
    select field1, field2, field3
    from tableA
    can I store this above data and return the values to jsp page and later used this in either jsp / java file.
    in the jsp file I will need to display only field1
    anyway can I do the above.

    When you submit the form, the request.getParameter("fieldname"); in the servlet (or JSP which is a specialized servlet) will give you the selected customer name. Execute a query like
    SELECT CustomerNumber, CustomerAddress FROm CustomerTable WHERE CustomerName = ?The ? corresponds to the selected customer name [If you are using PreparedStatement, which you should preferably, the query will have ? for the parameters and you need to set them].
    Define a class with getters/setter to hold the data. Like -
    public class CustomerBean {
        // Member variables.
        private String customerName     = null;
        private int customerNumber      = null;
        private String customerAddress  = null;
        // Getter methods
        public String getCustomerName()    { return this.customerName;    }
        public int getCustomerNumber()     { return this.customerNumber;  }
        public String getCustomerAddress() { return this.customerAddress; }
        // Setter methods
        public void setCustomerName(String customerName) {
            this.customerName = customerName;
        public void setCustomerNumber(int customerNumber) {
            this.customerNumber = customerNumber;
        public void setCustomerAddress(String customerAddress) {
            this.customerAddress = customerAddress;
    }As you loop over the ResultSet from the query, create an object for each record to hold the data and add each object to the ResultSet. Set this List as a request (or session, depending on the requirements - a request attribute will exist only till the request is executed i.e. for one navigation; session attribute will exist as long as the session exists). Retrieve the List from the request (or session) attribute and populate the other information, in whatever manner you wish, on the JSP.

  • 2D Vector or ArrayList

    Evening,
    Is there anything like a 2D Array in the ArrayList or Vector??

    Hi All.
    I am translating soem code from C++ to JAVA.
    in C++, I used vector< vector <int> > to create a sparse matrix / 2D array.
    I know you can make a vector of vectors in JAVA but i have been unable to get the individual elements. For example. I have:
    =========================
    Vector matrix = new Vector();
    for(){
    Vector row = new Vector();
    ... Do some to initiate row so that it has size > 1...
    matrix.add(row);
    =========================
    I can only do matrix.get(int), which gives me the entire row, but i can't do matrix.get(int).get(int) etc.... is there any way I can extract the[i] i,j element if a sparse matrix is set up this way or would i have to totally restructure?
    Thanks

  • Vector or ArrayList?

    Hi
    The J2ME-Polish framework provides an implementation of ArrayList. I am concerned in our project about the resource usage. Does anybody of you has experience with the ArrayList? Does it use less resources than the Vector?
    Kind regards
    Michael

    Hi
    The docs from J2ME Polish state that "de.enough.polish.util.ArrayList offers a fast alternative for Vector." I don't think though you would notice any difference when using one or another; you would have to make heavy use of this classes, which is not indicated in J2ME.
    I don't know if we can apply the J2SE concepts for this two classes, but you should read this article and decide what to use: http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-0622-vector.html
    Mihai

  • Vector vs ArrayList

    Is it better to use a Vector or an ArrayList to store objects?? and why?

    If you have multiple Threads and they access the same ArrayList, you can run into concurrency problems because the structure is not synchronized. Vector doesn't have this problem, all of its methods are sync. Using the ArrayList external sync call will make it about as slow as a Vector, if not slower.
    http://java.sun.com/docs/books/cp/
    The book on concurrent programming.
    http://g.oswego.edu
    The site on concurrent programming.. util.concurrent

  • Using a vector / array/ arraylist. .   something!  . . . to return an image

    I'm trying to create a class with a method that randomly returns one of five images. I can't figure out how to do it. Everything I try goes wrong because I can't figure out what kind of object to create in the method. My latest attempt (below) was with ArrayList, but the compiler keeps telling me:
    smallPix2.java:32: array required, but java.util.ArrayList found
         return icons[num];
    Here's the code. Any feedback appreciated:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    //import java.util.ArrayList;
    //import java.util.Arrays;
    //import java.util.Random;
    public class smallPix2 extends JFrame {
         ImageIcon img1 = new ImageIcon("Art//boutet.jpg");
         ImageIcon img2 = new ImageIcon("Art//curlu.jpg");
         ImageIcon img3 = new ImageIcon("Art//helleu.jpg");
         ImageIcon img4 = new ImageIcon("Art//ranson.jpg");
         ImageIcon img5 = new ImageIcon("Art//zamora.jpg");
    ImageIcon picks() {
         ArrayList icons = new ArrayList();
         icons.add(img1);
         icons.add(img2);
         icons.add(img3);
         icons.add(img4);
         icons.add(img5);
         Random rando = new Random();
         int num = rando.nextInt(5);
         return icons[num];
    }

    you have defined icons to be an ArrayList. So to reterieve data from it you should use its get() method.
    icons.get(num);if you look at the ArrayList API, this will return a type Object. You obviosly want to return an ImageIcon, and seeings you know that they are ImageIcons in there you can cast the object to ImageIcon:
    return (ImageIcon)icons.get(num);

  • Can i know what type of object is stored in Vector?

    i have written a program for vector where i am adding elements like
    sunday, monday , 3.14, 9,5.56 and i want to sum all elements of type double only double data type numbers. it should not add int number or string ?
    import java.util.*;
    class VectorBasic
         public static void main(String args[ ])
              Vector v1=new Vector(1);
              Double d1=new Double(3.14);
              v1.addElement(d1);
              v1.addElement("sunday");
              v1.addElement(new Integer(2));
              v1.addElement(new Double(5.56));     
              v1.addElement(new Integer(5));
              for (int i=0;i<v1.size();i++ )
              System.out.println(v1.elementAt(i));
    }

    Questions:
    1: Why are you using Vector? You should be using ArrayList in most new code. If you need synchronization (Vector is synchronized), use Collections.synchronizedList(). You don't need synchronization for the code you showed.
    2: Why initialize the size of Vector (or ArrayList) as 1? That just makes you have to reallocate the size of the list (done for you by the Vector class) as soon as you add a second element. Why not just use a new Vector() [or, better, a new ArrayList()] with the default size?
    3: Why are you mixing type in your Vector in the first place? Is this just a test class to learn how to tell the type of an object?
    Comment:
    1. You should use Double.valueOf(3.14) and Integer.valueOf(2), instead of calling "new Double(3.14)" and "new Double(2)".
    In the future, when posting code, use the code tags to keep it formatted nicely. There's a button for it above the posting box. Select your code, then press that "code" button. It will put code tags around your code. You can also type the tags manually--put one at the beginning of your code, and one at the end:

  • Vector loosing values of object?

    Hello, hope someone can help me out a bit on this issue that i'm encountering
    in the following code am reading pixel values from a raster (image) and storing the relevant ones in a Vector, however am encountering a problem in the last "if statement" as the vector is not storing the right values that are printed on screen but rather storing the values set by: currentPixel.setBlank();
    i cannot determine the reason for this behaviour since the "currentPixel" object is stored before the currentPixel.setBlank() method. Also what is puzzling me more is that the values in the println command are being displayed correctly! however when i dump all the values of the vector on screen the values are those assigned by currentPixel.setBlank() method;
    for (int h=0;h<height;h++){
                for (int w=0;w<width;w++){
                    position = (h*width)+w;
                    previousPixel = new PixelHolder();
                    previousPixel = currentPixel;
                    currentPixel = new PixelHolder();
                    currentPixel.setValue(pixelStore[position]);
                    currentPixel.setX(w);
                    currentPixel.setY(h);
                    previous = previousPixel.value;
                    current = currentPixel.value;
                    if (previous > current){
                        System.out.println(" pixel:"+ previousPixel.positionX+","+previousPixel.positionY+","+ previousPixel.value );
                        //store previousPixel;
                        myPixelVector.addElement(previousPixel);
                    } else if (current > previous){
                        bufferPixel = new PixelHolder();
                        bufferPixel = previousPixel;
                        buffer = bufferPixel.value;
                    if ((w == width-1) && (current > buffer)){
                        //store currentPixel;
                        System.out.println("3rd phase currentpixel:"+ currentPixel.positionX+","+currentPixel.positionY+","+ currentPixel.value );
                        myPixelVector.add(currentPixel);  //problems here..
                        bufferPixel.setBlank();
                        currentPixel.setBlank();
    setBlank method from PixelHolder();:
    public void setBlank(){
        positionX = 0;
        positionY = 0;
        value = 0;
    }output by : System.out.println("3rd phase currentpixel:"+ currentPixel.positionX+","+currentPixel.positionY+","+ currentPixel.value );:
    previous pixel:178,63,106
    3rd phase currentpixel:179,63,105
    output by displaying contents of myPixelVector on screen (note the last three values tally in the first line, whereas in second line these are as per the setBlank method):
    i: 3289,178,63,106
    i: 3290,0,0,0
    hope any one can brighten my thoughts up as i am really lost with this one!
    thanks a lot!
    S

    the problem is that when you are adding currentPixel to the Vector, you are adding the instance being pointed to by currentPixel, which retains the pointer. Thus when you setBlank currentPixel, you are blanking the instance which is also being referenced in the Vector.
    A way around it is to add a clone of the pixel to the Vector - make sure the clone method is implemented in that class.
    E.g. myPixelVector.add(currentPixel.clone());
    Hope this Helps!
    Jon

  • Problem with Vector method addElement

    I am new to Java. I am using JDK 1.3. I am writing a program that will convert a text file to a binary file that stores a Vector object. I have narrowed my problem to the method that reads the text file and creates my vector. Each element in my vector stores an integer and a string variable. The reading of the text file works find and the creation of my record works find. It seems that the storing of the record in the vector is not working. When I print the first 10 elements of the vector, it have the same record(the last record of my text file). What is wrong with the method below? I am also appending the result of running my program.
    private static void readTextFile(File f) {
    try {
    FileReader fileIn = new FileReader(f);
    BufferedReader in = new BufferedReader(fileIn);
    String line;
    int i;
    SsnLocationRecord recordIn = new SsnLocationRecord();
    int ctr = 0;
    while (true) {
    line = in.readLine();
    if (line == null)
    break;
    ctr += 1;
    i = line.indexOf(" ");
    recordIn.putAreaNumber(Integer.parseInt(line.substring(0,i).trim()));
    recordIn.putLocation(line.substring(i+1).trim());
    records.addElement(recordIn);
    if (ctr < 11)
    System.out.println(recordIn);
    in.close();
    } catch (IOException e) {
    System.out.println ("Error reading file");
    System.exit(0);
    for (int i = 0; i < 11; i++)
    System.out.println((SsnLocationRecord) records.elementAt(i));
    RESULTS:
    C:\Training\Java>java ConvertTextFileToObjectFile data\ssn.dat
    0 null
    3 New Hampshire
    7 Maine
    9 Vermont
    34 Massachusetts
    39 Rhode Island
    49 Connecticut
    134 New York
    158 New Jersey
    211 Pennsylvania
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    C:\Training\Java>

    First of all it would be better if you did a priming read and then checked line == null in the while statement instead of the way you have it.
    ctr++ will also accomplish what ctr +=1 is doing.
    you need to create a new instance of SsnLocationRecord for each line read. What you are doing is overlaying the objects data each time you execute the .putxxxx methods. The reference to the object is placed in the vector. The actual object is still being updated by the .putxxx methods (NOTE : THIS IS THE ANSWER TO YOUR MAIN QUESTION).
    you close should be in a finally statement.
    To process through all the elements of a Vector create an Enumeration and then use the nextElement() method instead of the elementAt is probably better. (Some will argue with me on this I am sure).
    Also, on a catch do not call System.exit(0). This will end your JVM normally. Instead throw an Exception (Runtime or Error level if you want an abnormal end).

  • Vector  or Array List better usage

    Hi form
    For storage of large Object's Which is a better management API
    Vector OR ArrayList
    Please some one Enlightern me
    with regards
    Karthik

    Please some one Enlightern meObjects in Java are always handled using references (pointers) to the actual object values (which reside on the so called heap).
    So from the point of the size of the objects, Vector and ArrayList are equivalent. No object values are stored in them, only references to objects and references always have the same size.

  • What is the Proper way to nullify the VECTOR after it's scope is over

    I am using Vectors and Array lists at many places in my Web Application, It is neccessary to use them.
    In some processes I m storing bulk amount of data into vector due to that the performance of my application will be decreased, for that I have to nullify the vector after it's scope is over.
    To nullify I m using Vector v = new Vector()
    v.clear().
    The above method is suitable in case of simple object data like strings and other values.
    But I wanna know that If I m using HashMap and storing bulk data in it and then I m storing each HashMap into vector, what is the proper way.
    Does I have to iterate each object of HashMap from vector and set them as null and then set vector as null or directly I can use v.clear() method??
    If any having any answer regarding my question then plz reply your each valuable reply will be appriciable.
    Thanks in advance......!!

    JBOSS2000 wrote:
    Each time in loop a new object of vector is created and each time I m nullifying it. Thats what I m doing.
    Thats why I m nullifying it.
    Even if I'll declare it out side the loop then also for the each iteration I have to nullify it cause what I m doing is I m inserting the data into database in each iteration of loop, So that I think it is must to nullify the objects each time.If it is constructed inside the loop then you do not have to nullify it. If it is constructed outside of the loop and you want to empty it for each iteration then just clear() it.

  • Capture Coordinates of All Content with a PDF

    Is it possible to have a script extract the coordinates of all content - mostly vector paths (lines and curves) from specific layers of a pdf and to export that information to an XML file? I would also need it to include the color and lineweight information.
    I have noticed comments where you can get the quadrants of text using "getPageNthWordQuads."  I am looking for something similar where I can extract all paths, lines, shapes and other objects within the pdf.  This can be achieved in Adobe Illustrator using a script but I am looking for something web-based if possible.
    Thanks,
    Rebecca

    Actually Acrobat doesn't handle ActionScript in the way you seem to be suggesting - you can't script at the document-level with AS like you can with JavaScript.  Acrobat now comes with an embedded Flash engine which will allow you to render document-level Falsh content even if the client machine doesn't have Flash Player installed, and also allows you to interact with the Flash content but you cannot simply write script in AS and embed that in a PDF.  None of the interfaces that you can import into your Flash content to interact with the PDF will allow you this level of access either.
    As I mentioned earlier, the only way you could do this is with a plug-in written in C/C++.

  • Asking about Vector

    Hi ,
    I will like to ask about the Vector class. I tried to use the ElementAt method and when i declared the code as below :
         int arrayelement = insertarray.elementAt(tempsize);it will give me an error saying object needed.
    then if i put as String as below :
    String arrayelement = (String)insertarray.elementAt(tempsize); it can worked. Does this mean that for ElementAt ,we have to case it to String and not integer?? Hopw someone can enlighten me :P
    Thanks

    "int" is not an object, it is a primitive type. Vector can store only objects and so elementAt can return only objects; you get the error because it's impossible to get int from a general object.
    If you want to store integers in the vector you can use objects of the class Integer, that class wraps the primitive type int:    insertArray.add(new Integer(42));
        Integer object = (Integer) insertArray.elementAt(0);
        int value = object.intValue();

Maybe you are looking for