ArrayList concept

Hi,
I know how to add elements in ArrayList,
My requirement is
ArrayList al=new Arraylist();
al.add(12);//this is my requirement i need code for these method can u able to send successful code.
I know we can add like this
al.add(new Float(12.090909));
but I need add(12);

ArrayList al=new Arraylist();
al.add(12);//this is my requirement i need code for
these method can u able to send successful code.If I am allowed to take this very literally, I can solve your problem. Declare a class Arraylist (with a lowercase l) that extends ArrayList (which has a capital L) and provide a method add(int). You're done.
That was intended to be a joke!
Seriously, either box your int into an Integer before adding to the ArrayList, or write your own int list class. The latter may or may not use ArrayList for implementation, either through inheritance or composition. Only, give it a descriptive name, list IntArrayList, for example.

Similar Messages

  • Very Basic..  Array list Concept.. using two arraylist..

    Hello all,
    Please clear my Arraylist concept.. the problem is that I am using two arraylist one.. in Spriteframe, and other in SpriteFramecollection.. and adding objects to them..
    the problem comes when am adding new frame to framecollection.. instead of adding new.. it changes all previous frames too.. I want to reflect change only in latest one..
    Lets explain me in detail..
    I have used like
    class Project..
         ---> Calculate Button
         ---> MultipleMove Button
         ---> Save Button
    In Calculate class..
         Sprite st = new Sprite();
         SpriteFrame sframe = new SpriteFrame();
         ..// I do some calculation
         st.newSprite(croppedimage, file, 0, 0, number, 0, 0);         //here am creating sprite
         sframe.addSprite(st);                            //here am adding sprite to Spriteframe
    In MultipleMove class..
         SpriteFrame sframe = new SpriteFrame();
         // do some adding and deleting of sprites in frame
    In save class..     //Problem comes here.. Am going crazy!!
         SpriteFrameCollection sframecoll = new SpriteFrameCollection();
         SpriteFrame frame = new SpriteFrame();
    --->     sframecoll.addSpriteFrame(frame);     <------- // am just adding frame to framecollection
         }Now when I am printing elements of Sprite.. frame1, and frame2 gets changed simultaneously.. I mean why frame1 also gets changed..
    am just adding new SpriteFrame.. to spriteframecollection..
    please someone tell me what is wrong in my concept of understanding arraylist..
    as making class objects again and again wrong..
    what should I do to add only newly Frame to framecollection??.. why all previous frame gets changed too.. ??
    gervini
    I have class Sprite, SpriteFrame, SpriteFrameCollection as shown below..
    import java.io.*;
    import java.awt.Image;
    public class Sprite               // Each single sprite
         Image img;
         File file;                 // is filepath where this sprite is located
         int xcord,ycord;           // xcoord,ycoord are real position in frame
         int numberinfile;           // this is the position of the sprite in the raw file
         int mirrorh, mirrorv;      // for normal=00,horizontal=10,vertical=01,both=11
         void newSprite(Image img, File file, int xcord, int ycord, int numberinfile, int mirrorh, int mirrorv)
              this.img = img;
              this.file = file;
              this.xcord = xcord;
              this.ycord = ycord;
              this.numberinfile = numberinfile;
              this.mirrorh = mirrorh;
              this.mirrorv = mirrorv;
    import java.io.*;
    import java.util.*;
    public class SpriteFrame                          // Full One Frame consisting of many sprites..
         static ArrayList spritelist = new ArrayList();               // arraylist containing many sprites
         void addSprite(Sprite sprite)
             spritelist.add(sprite);                              
        void removeSprite(Sprite s)
             spritelist.remove(s);
    import java.io.*;
    import java.util.*;
    public class SpriteFrameCollection                    // Consisting of many frames..
         static ArrayList spriteframelist = new ArrayList();          // Arraylist of many frames
         void addSpriteFrame(SpriteFrame spriteframe)
              spriteframelist.add(spriteframe);
        void removeFrame(SpriteFrame sf)
             spriteframelist.remove(sf);
    }

    It is hard to see what it coursing your problems becouse you only posted axtracts from your code. However I think that it is becouse every time you want to access the methods in SpriteFrame you ar creating a new object. Every time you create a new Strite fram a new, empty ArrayList is being created. What you want to do is create this only once, and pass this instance to the parts of your code that need it.
    Let me try to explain this using a matphor. 2 people are trying to make some tea. One person has access to water and another has access to teabags. Both of them know that there is such a thing as a kettle. What you are doing is; person 1 is creating a kettle and filling it with water. Then person 2 is creating a new kettle and trying to pour the water from it. obviously this doesn't work. You want person 1 to creat a kettle, fill it with water and then pass that kettle to person 2. person 2 takes this kettle and then pours the water from it.

  • Arraylist polymorphism concept

    Can you please explain why both the below statements compile? Animal is the superclass and Dog the subclass.
    I am not able to understand the meaning of the statement even.
    ArrayList<Dog> dogs1 = new ArrayList<Animal>();
    ArrayList<Animal> animals = new ArrayList<Dog>();

    Mehta wrote:
    Head First Java 2nd edition Page No. 579 says it should compile. Even i am not able to compile.
    Any comments....Seeing is believing. If you try to compile the exact same code, and it doesn't compile, then obviously, it doesn't compile. No matter what the book says.

  • Adding to an ArrayList

    I have been staring at this for 2 days now, and finally decided to ask the experts.
    I have a method of a class that should fetch records from a (textual) database en return an ArrayList with all the records. Each record in turn should contain all the (4) fields.
    Well, it pretty much all works fine, except for the fact that the line 'dbRecs.add(rec)' overwrites ALL ArrayList elements with the new record, instead of just the last. That is, I presume this is the case, since this is what a spying-loop showing the content af all the entries of the ArrayList (not included in the code, but added right after the wretched line) tells me.
    The code shows the method, and the class of the records with the fields.
    Any enlightenment on what the ... is wrong would be greatly appreciated.
    public ArrayList getDbRecords() {
              ArrayList dbRecs;
              String dbLine;
              String[] splitstring;
              dbRecs = new ArrayList(15);
              DbRecord rec;
              BufferedReader in;
              try {
                   FileInputStream fstream = new FileInputStream(SystemVars.dbFileName); // Open the file
                   in = new BufferedReader(new InputStreamReader(fstream));
                   rec = new DbRecord();
                   int i = 0;
                   while ((dbLine = in.readLine()) != null) { // Continue to read lines until eof
                        i++;
                        splitstring = dbLine.split("\"");
                        rec.proverb     = splitstring[1];
                        rec.nl = splitstring[3];
                        rec.transl = splitstring[5];
                        rec.extra = splitstring[7];
                        dbRecs.add(rec); //add record to ArrayList
                   } //end 'while'
                   in.close();
         catch (Exception e) {
                   System.err.println("File input error");
              dbRecs.trimToSize();
              return(dbRecs);
    class DbRecord {
         String proverb,nl,transl,extra;
    }

                   rec = new DbRecord();
                   int i = 0;
    while ((dbLine = in.readLine()) != null) { //
    // Continue to read lines until eof
                        i++;
                        splitstring = dbLine.split("\"");
                        rec.proverb     = splitstring[1];
                        rec.nl = splitstring[3];
                        rec.transl = splitstring[5];
                        rec.extra = splitstring[7];
    dbRecs.add(rec); //add
    /add record to ArrayList
    } //end
    end 'while'This is a real conceptual error. You are initialising the object outside the while loop and adding it to the list inside the loop. Everytime you reference the same object and the arraylist does nothing more than storing the references to them.
    The solution is to initialise the object each time in the loop, so that every object in the arraylist would refer to a different object.
    Another thing that I noticed is that the code is rather sloppy. You seem to have bypassed the concept of encapsulation totally... which defeats the very purpose of OOP. Make the member variables private and use getter/setter methods to access them.
    Phew!
    ***Annie***

  • Doubts in GeoRaster Concept.

    Hi everybody,
    I have few doubts in GeoRaster concepts.
    I did mosaicing of multiple Georasater objects using "sdo_geor.getRasterSubset()" and able to display image properly. But while doing this I come across few people suggestions. They said that mosaicing multiple rows together in a GeoRaster table is not going produce meaningful results because the interpolation methods wont have access to the data in the adjacent cells at the seams because cell needed exist in a different row (i.e. where two rows of GeoRaster either abut or overlap).
    I assume Oracle takes care of all this. Please suggest wheather my assumption is true or the statement given is true?
    Regards,
    Baskar
    Edited by: user_baski on May 16, 2010 10:49 PM

    Hi Jeffrey,
    Requirements:-
    I have to do mosaicing of 'n' number of Georaster objects. For eg, if table has 4 rows of GeoRaster object, then i have to create single image by mosaicing all the Georaster object based on the Envelope provided. (Note: I have to do this with Queries without using GeoRaster API)
    Workflow:-
    1. Get the connection and table details.
    2. Retrieve necessary information from the db like SRID, MAXPYRAMID, SPATIALRESOLUTION, EXTENT etc. For getting extent, I used SDO_AGGR_MBR function.
    3. With the help of "MDSYS.SDO_FILTER" and bouding box values, I create arraylist which contains raster id's retrieved from raster data table which covers the bouding box value provided in the filter command.
    4. Then I passed bounding box value into "sdo_geor.getCellCoordinate" function and I retrieved row and column number of Georaster image and created a number array which contains starting and ending row/column numbers.
    5. Then I had written a PL/SQL with "sdo_geor.getRasterSubset" function which takes the number array and raster id as input parameters, which inturn returns BLOB object.
    6. I am executing step 5 in a loop with all the raster id's that I got at step 3. For eg, arraylist size is 4, then I will have four BLOB object.
    7. Finally, I creating new image from the BLOB objects after some scaling and cropping based on the individual GeneralEnvelope of each raster id object.
    I had followed all the above steps and successfully created mosaic image.However, few people suggested that mosaicing in this way does not produce meaningful results because the interpolation methods wont have access to the data in the adjacent cells at the seams because cell needed exist in a different row. I assume Oracle will take care of these things. Moreover, they suggested to keep single row in GeoRaster table instead of muliple rows of Georaster object and suggested to use "SDO_GEOR.updateRaster" function to update a part of the raster object and the pyramids are rebuild automatically.
    So Please suggest which is the better way to do mosaicing. Wheather my assumption is correct or not?

  • How to use Multimaps (Map String, ArrayList String )

    I was using an array to store player names, userIDs, uniqueIDs, and frag counts, but after reading about multimaps in the tutorials, it seems that would be much more efficient. However, I guess I don't quite understand it. Here's how I wanted things stored in my string array:
    String[] connectedUsers = {"user1_name", "user1_userid", "user1_uniqueid", "user1_frags"
                                            "user2_name"...}and here is how I'm attempting to setup and use the 'multimap':
    public class Main {
        static Map<String, ArrayList<String>> connectedUsers;
        public void updatePlayers(String name, String status) {
            String[] statusSplit = status.split(" ");
            if (connectedUsers.containsKey(name)) {
                connectedUsers.put(name, statusSplit[0]);
            else {
                connectedUsers.put(name, statusSplit[0]);
        }It's quite obvious I don't understand how this works, but should I even set this multimap up this way? Perhaps I should use a regular map with a string array for the values?

    You're cool MrOldie. Its just that alarm bells start ringing in my head when people come on and post as much as you do.
    * Created on Jul 28, 2005 by @author Tom Jacobs
    package tjacobs;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeSet;
    * ManyMap is a map that allows more than one value to be stored with any key
    * <p>
    * There are a number of methods in the class that have been deprecated because
    * the original functionality of Map has been violated to accomodate the concept
    * of the ManyMap
    public class ManyMap<T, T2> implements Map<T, T2> {
         private HashMap<T, ArrayList<T2>> mInnerMap;
         public ManyMap() {
              mInnerMap = new HashMap<T, ArrayList<T2>>();
          * @deprecated
         public T2 get(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.get(0);
         public Iterator<T2> getAll(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.iterator();          
         public T2 put(T obj1, T2 obj2) {
              ArrayList<T2> ar = _getNotNull(obj1);
              ar.add(obj2);
              return obj2;
         public Set<Map.Entry<T, T2>> entrySet() {
              TreeSet<Map.Entry<T, T2>> entries = new TreeSet<Map.Entry<T, T2>>();
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   Iterator<T2> vals = mInnerMap.get(key).iterator();
                   while (vals.hasNext()) {
                        Entry<T, T2> entry = new Entry<T, T2>(key, vals.next());
                        entries.add(entry);
              return entries;
         public int size() {
              return mInnerMap.size();
         public int valuesSize() {
              int vals = 0;
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   ArrayList<T2> ar = mInnerMap.get(key);
                   vals += ar.size();
              return vals;
         public void clear() {
              mInnerMap.clear();
         public void putAll(Map<? extends T, ? extends T2> map) {
              Iterator _i = map.entrySet().iterator();
              while(_i.hasNext()) {
                   Map.Entry<? extends T, ? extends T2> entry = (Map.Entry<? extends T, ? extends T2>) _i.next();
                   put(entry.getKey(), entry.getValue());
         public Collection <T2> values() {
              LinkedList ll = new LinkedList();
              Iterator<ArrayList<T2>> _i = mInnerMap.values().iterator();
              while (_i.hasNext()) {
                   ll.addAll(_i.next());
              return ll;
         public boolean containsValue(Object val) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              while (values.hasNext()) {
                   if (values.next().contains(val)) return true;
              return false;
         public boolean containsKey(Object key) {
              return mInnerMap.containsKey(key);
         public T2 remove(Object obj) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              boolean found = false;
              while (values.hasNext()) {
                   if (values.next().remove(obj)) {
                        found = true;
              return found ? (T2)obj : null;
         public boolean isEmpty() {
              return valuesSize() == 0;
         @SuppressWarnings("hiding")
         private class Entry<T, T2> implements Map.Entry<T, T2> {
              T key;
              T2 val;
              public Entry (T obj1, T2 obj2) {
                   key = obj1;
                   val = obj2;
              public T2 getValue() {
                   return val;
              public T getKey() {
                   return key;
              public T2 setValue(T2 obj) {
                   return val = obj;
         public Set<T> keySet() {
              return mInnerMap.keySet();
         public ArrayList<T2> _get (Object obj) {
              return mInnerMap.get(obj);
         public ArrayList<T2> _getNotNull (T obj) {
              ArrayList<T2> list = _get(obj);
              if (list == null) {
                   list = new ArrayList<T2>(1);
                   mInnerMap.put(obj, list);
              return list;
    }Edited by: tjacobs01 on Aug 19, 2008 12:28 PM

  • Inheritance and ArrayList

    I am working on a natural-language processing system in Java. The first step of my approach is to "parse" a sentence and create a representation of it in Java(i.e. "large" would correspond to an object of class large). The issue is that I basically want to create an ArrayList that contains Java's representation of the sentence, which, for the example sentence "a large cat is sitting on my bed" would contain objects of type "large", "cat", "sit", "my", and "bed". Since an ArrayList can only hold one type of object, could I create a "sentence" class that was extended by all of the individual concept classes, and make the ArrayList be that class?(While still being able to use methods in the child classes)

    Since an ArrayList can only hold one type of objectWrong. It can contain many kinds of diffrent objects, unless you specify it generically to only be able to store 1 kind of object.
    could I create a "sentence" class that was extended by all of the individual concept classes, and make the ArrayList be that class?Yes.
    (While still being able to use methods in the child classes)No. As the superclass will work as a kind of interface(Which means that only the methods specifyed in the superclass will be reachable directly, ofcourse you can get the object from the ArrayList and once more specify that it is 1 of the subclasses, and then call for its "sub-methods").
    Also if ur gonna go on about this, you should make the "sentence" class an interface, as you can make the methods do diffrent stuff in the diffrent classes then, even tho they are named the same.
    edit: Edited a misstype, in the first sentence lol.
    Edited by: prigas on Aug 3, 2008 11:19 AM

  • How do I get an arrayList from an external class

    I have 3 classes. 1 is used to create a contact object. 2 is for my GUI 3 Does all the buisness logic. I need to get an updated arrayList back from class 3 to display the contents in my GUI class. Can someone give me a snipet. I know hat to do from there so am only looking for code to get my updated ArrayList.
    If you need to see a snipet of code ask.

    Here are my Buissness Layer and my GUI the other class is just and object class. Do I have the correct MVC concept or can I improve? If so how?
    In addition I made my arrayList more visible(loads of ///////////////////////////////////// around them) can u tell me if this is correct will I be able to CRUD(the arrayList) as it is, meaning if it correctly laid out between the 2 classes for me to work on? Last thing... I think my arrayLists are creating an xlint error and I cant pick it up in compiler can soemoene point out why?
    GUI class...
         Filename:     ContactsListInterface.java
         Date:           16 March 2008
         Programmer:     Yucca Nel
         Purpose:     Provides a GUI for entering names and contact numbers into a telephone directory.
                        Also allows options for searching for a specific name and deleting of data from the record
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Phonebook1 extends JFrame implements ActionListener
    { //start of class
         // construct fields, buttons, labels,text boxes, ArrayLists etc
         JTextPane displayPane = new JTextPane();
         JLabel listOfContacts = new JLabel("List Of Contacts");               // creates a label for the scrollpane
         JButton createButton = new JButton("Create");
         JButton searchButton = new JButton("Search");
         JButton modifyButton = new JButton("Modify");
         JButton deleteButton = new JButton("Delete");
         Contact c = new Contact();
         ArrayList<Person> contactList = c.getList();
         // create an instance of the ContactsListInterface
         public Phonebook1()
         { // start of cli()
              super("Phonebook Interface");
         } // end of cli()
         public JMenuBar createMenuBar()
         { // start of the createMenuBar()
              // construct and populate a menu bar
              JMenuBar mnuBar = new JMenuBar();                              // creates a menu bar
              setJMenuBar(mnuBar);
              JMenu mnuFile = new JMenu("File",true);                         // creates a file menu in the menu bar which is visible
                   mnuFile.setMnemonic(KeyEvent.VK_F);
                   mnuFile.setDisplayedMnemonicIndex(0);
                   mnuFile.setToolTipText("File Options");
                   mnuBar.add(mnuFile);
              JMenuItem mnuFileExit = new JMenuItem("Save And Exit");     // creates an exit option in the file menu
                   mnuFileExit.setMnemonic(KeyEvent.VK_X);
                   mnuFileExit.setDisplayedMnemonicIndex(1);
                   mnuFileExit.setToolTipText("Close Application");
                   mnuFile.add(mnuFileExit);
                   mnuFileExit.setActionCommand("Exit");
                   mnuFileExit.addActionListener(this);
              JMenu mnuEdit = new JMenu("Edit",true);                         // creates a menu for editing options
                   mnuEdit.setMnemonic(KeyEvent.VK_E);
                   mnuEdit.setDisplayedMnemonicIndex(0);
                   mnuEdit.setToolTipText("Edit Options");
                   mnuBar.add(mnuEdit);
              JMenu mnuEditSort = new JMenu("Sort",true);                    // creates an option for sorting entries
                   mnuEditSort.setMnemonic(KeyEvent.VK_S);
                   mnuEditSort.setDisplayedMnemonicIndex(0);
                   mnuEdit.add(mnuEditSort);
              JMenuItem mnuEditSortByName = new JMenuItem("Sort By Name");          // to sort entries by name
                   mnuEditSortByName.setMnemonic(KeyEvent.VK_N);
                   mnuEditSortByName.setDisplayedMnemonicIndex(8);
                   mnuEditSortByName.setToolTipText("Sort entries by first name");
                   mnuEditSortByName.setActionCommand("Name");
                   mnuEditSortByName.addActionListener(this);
                   mnuEditSort.add(mnuEditSortByName);
              JMenuItem mnuEditSortBySurname = new JMenuItem("Sort By Surname");     // to sort entries by surname
                   mnuEditSortBySurname.setMnemonic(KeyEvent.VK_R);
                   mnuEditSortBySurname.setDisplayedMnemonicIndex(10);
                   mnuEditSortBySurname.setToolTipText("Sort entries by surname");
                   mnuEditSortBySurname.setActionCommand("Surname");
                   mnuEditSortBySurname.addActionListener(this);
                   mnuEditSort.add(mnuEditSortBySurname);
              JMenu mnuHelp = new JMenu("Help",true);                                        // creates a menu for help options
                   mnuHelp.setMnemonic(KeyEvent.VK_H);
                   mnuHelp.setDisplayedMnemonicIndex(0);
                   mnuHelp.setToolTipText("Help options");
                   mnuBar.add(mnuHelp);
              JMenuItem mnuHelpHelp = new JMenuItem("Help");                              // creates a help option for help topic
                   mnuHelpHelp.setMnemonic(KeyEvent.VK_P);
                   mnuHelpHelp.setDisplayedMnemonicIndex(3);
                   mnuHelpHelp.setToolTipText("Help Topic");
                   mnuHelpHelp.setActionCommand("Help");
                   mnuHelpHelp.addActionListener(this);
                   mnuHelp.add(mnuHelpHelp);
              JMenuItem mnuHelpAbout = new JMenuItem("About");                         // creates a about option for info about api
                   mnuHelpAbout.setMnemonic(KeyEvent.VK_T);
                   mnuHelpAbout.setDisplayedMnemonicIndex(4);
                   mnuHelpAbout.setToolTipText("About this program");
                   mnuHelpAbout.setActionCommand("About");
                   mnuHelpAbout.addActionListener(this);
                   mnuHelp.add(mnuHelpAbout);
              return mnuBar;
         } // end of the createMenuBar()
         // create the content pane
         public Container createContentPane()
         { // start of createContentPane()
              //construct and populate panels and content pane
              JPanel labelPanel = new JPanel(); // panel is only used to put the label for the textpane in
                   labelPanel.setLayout(new FlowLayout());
                   labelPanel.add(listOfContacts);
              JPanel displayPanel = new JPanel();// panel is used to display all the contacts and thier numbers
                   setTabsAndStyles(displayPane);
                   displayPane = addTextToTextPane();
                   displayPane.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(displayPane);
                   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // pane is scrollable vertically
                   scrollPane.setWheelScrollingEnabled(true);// pane is scrollable by use of the mouse wheel
                   scrollPane.setPreferredSize(new Dimension(400,320));
              displayPanel.add(scrollPane);
              JPanel workPanel = new JPanel();// panel is used to enter, edit and delete data
                   workPanel.setLayout(new FlowLayout());
                   workPanel.add(createButton);
                        createButton.setToolTipText("Create a new entry");
                        createButton.addActionListener(this);
                   workPanel.add(searchButton);
                        searchButton.setToolTipText("Search for an entry by name number or surname");
                        searchButton.addActionListener(this);
                   workPanel.add(modifyButton);
                        modifyButton.setToolTipText("Modify an existing entry");
                        modifyButton.addActionListener(this);
                   workPanel.add(deleteButton);
                        deleteButton.setToolTipText("Delete an existing entry");
                        deleteButton.addActionListener(this);
              labelPanel.setBackground(Color.red);
              displayPanel.setBackground(Color.red);
              workPanel.setBackground(Color.red);
              // create container and set attributes
              Container c = getContentPane();
                   c.setLayout(new BorderLayout(30,30));
                   c.add(labelPanel,BorderLayout.NORTH);
                   c.add(displayPanel,BorderLayout.CENTER);
                   c.add(workPanel,BorderLayout.SOUTH);
                   c.setBackground(Color.red);
              // add a listener for the window closing and save
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             int answer = JOptionPane.showConfirmDialog(null,"Are you sure you would like to save all changes and exit?","File submission",JOptionPane.YES_NO_OPTION);
                             if(answer == JOptionPane.YES_OPTION)
                                  System.exit(0);
              return c;
         } // end of createContentPane()
         protected void setTabsAndStyles(JTextPane displayPane)
         { // Start of setTabsAndStyles()
              // set Font style
              Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
              Style regular = displayPane.addStyle("regular", fontStyle);
              StyleConstants.setFontFamily(fontStyle, "SansSerif");
              Style s = displayPane.addStyle("bold", regular);
              StyleConstants.setBold(s,true);
         } // End of setTabsAndStyles()
         public JTextPane addTextToTextPane()
         { // start of addTextToTextPane()
              int numberOfEntries = contactList.size();
              int count = 0;
              Document doc = displayPane.getDocument();
              try
              { // start of tryblock
                   // clear previous text
                   doc.remove(0,doc.getLength());
                   // insert titles of columns
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   for(Person person : contactList)
                        Person c = contactList.get(count);
                        doc.insertString(doc.getLength(),c.name,displayPane.getStyle("regular"));
                        count ++;
              } // end of try block
              catch(BadLocationException ble)
              { // start of ble exception handler
                   System.err.println("Could not insert text.");
              } // end of ble exception handler
              return displayPane;
         } // end of addTextToTextPane()
         // code to process user clicks
         public void actionPerformed(ActionEvent e)
         { // start of actionPerformed()
              String arg = e.getActionCommand();
              // user clicks create button
              if(arg.equals("Create"))
                   c.createNew();                                                  // method to create a new Contact
                   addTextToTextPane();
              if(arg.equals("Search"))
                   c.searchExisting();                                             // method to search for an existing entry
              if(arg.equals("Modify"))
                   c.modifyExisting();
              if(arg.equals("Delete"))
                   c.deleteExisting();
              if(arg.equals("Exit"))
         } // end of actionPerformed()
         // method to create a new contact
         public static void main(String[] args)
         { // start of main()
              // Set look and feel of interface
              try
              { // start of try block
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } // end of try block
              catch(Exception e)
              { // start of catch block
                   JOptionPane.showMessageDialog(null,"There was an error in setting the look and feel of this application","Error",JOptionPane.INFORMATION_MESSAGE);
              } // end  of catch block
              Phonebook1 pb = new Phonebook1();
              pb.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              pb.setJMenuBar(pb.createMenuBar());
              pb.setContentPane(pb.createContentPane());
              pb.setSize(520,500);
              pb.setVisible(true);
              pb.setResizable(true);
         } // end of main()
    } //end of classBuisness Layer.....
    import javax.swing.JOptionPane;
    import java.util.ArrayList;
    public class Contact
         ArrayList<Person> contactList = new ArrayList<Person>();               // To hold all the contacts
         Person p = new Person();                                                       // Create a instance of the  Person class
         int maxLength = 10;                                                                 // To be used as a boundary value for the Strings entered
         public void createNew()
              String firstName = getName("Create");
              if(firstName.trim().length() > maxLength)
                   JOptionPane.showMessageDialog(null,"You may not enter a name longer than "+maxLength+" chracters. Please try again","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();
              if(firstName == null)
                   finish();
              if(firstName.length() == 0)
                   JOptionPane.showMessageDialog(null,"You may not enter a blank name. Please try again.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();
              p.name = firstName.trim().toUpperCase();
              contactList.add(p);
         public void searchExisting()
         public void modifyExisting()
         public void deleteExisting()
         public String getName(String str)
              String strx = str;
              String firstName = JOptionPane.showInputDialog(null,"Please enter the name of the contact you wish to "+strx);
              if(firstName == null)
              finish();
              return firstName;
         public void finish()
              System.exit(0);
         public ArrayList getList()
              ArrayList<Person> list = contactList;
              return list;
    }Edited by: Yucca on Apr 17, 2008 4:48 PM

  • 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

  • Querying, then generating ArrayLists with variable names

    Hi, all:
    I have two problems: first, I want to run through an array list called nodeList containing Nodes, each of which possesses a 5-digit value called culture. I want each Node to try to find out whether or not there are any other Nodes that have the same culture value that it does, i.e. if Node i has culture value 74936 and there are 4 other Nodes with the same culture value, I need to find 5 total Nodes with culture value 74936.
      public void statistics(){
           for (int i = 0; i < nodeList.size (); i++) {
                Node node = (Node) nodeList.get (i);
                int cultSame = node.getCulture();
                boolean same = cultSame == next.cultSame;
                if (same == true){
                     arrayListCreator();
                     //generated Arraylist add.node;
      }I'm going astray at next.cultSame. I'm not sure how to structure the query to the ArrayList nodeList to find all the other Nodes with the same culture value.
    Second: I want to create a little method to generate ArrayLists with names based on the integers that will be stored in them. Here's the method so far:
      public void arrayListCreator () {
           String name = String.valueOf(cultSame);
           name = new Arraylist();
      }cultSame is a 5-digit integer. The ArrayLists will be used to store all the nodes with the same cultSame value, like 74936, or whatever. If the ArrayList is storing nodes with the cultSame value of 74936, I want the name of the ArrayList to be the string 74936. I want to call on this method (like you can see in the first method) to generate the ArrayList with its given name and then use it to store the nodes in it. Once I've done that, I can figure out the statistics stuff on my own, I think. I'm just not sure how to create the ArrayLists with a name that's a variable, i.e. "name" should be the string variable containing a 5-digit number.

    Nquirer101 wrote:
    I probably should have separated this out into two threads. First, I'd like to know what I'm doing wrong when I'm building that boolean query to find out in the nodeList if any of the other nodes have the same culture value as the node doing the querying.Then by all means do so, from the looks of it, the scope of the thngs that need to be discussed/addressed is too broad for one thread. First there's the issue of your erroneous understanding of variable, then there's the concept of the Map data structure, then the implementation of it in Java, along with the idea of interface

  • Reg: ArrayList

    Hi All,
    I have a ArrayList in my application and some objects are added to that arraylist for ex: "arr.add("document"); 
    I am unable to understand the concept of this arraylist. What type of attributes can be added to arraylist.
    Thanks in advance.

    Hi Bharath,
                      Check this:
    <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html">http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html</a>
    regards
    Sumit

  • Invalidate concept for value node and model node

    Hello everybody,
    We have invalidate method for value node and model node.
    I want to know basic concept behind this method.
    What this method acually does?
    Regards,
    Bhavik

    Hi Pran and all,
    I figured out the problem. Input parameters are going multple times. So, depending upon that it gives multiple values.
    My scenario is:
    Root Node
    |_ Input_node1
         |_Attr1
    |_ Input_Node2
         |_Attr2
    |_Output_node
         |_Result
    I am passing values in Attr1 and Attr2 attributes.
    For this, first of all, i wrote following code.
    In controller, i have initialized Root node:
    Root_Node model = new Root_Node();
    wdcontext.nodeRoot_Node().bind(model);
    In view, I set values for attr1 and attr2 using following code:
    Ipublic<View>.IInput_node1Element ele = wdcontext.createInput_node1Element();
    ele.setAttr1("<value>");
    wdcontext.nodeInput_node1().addElement(ele);
    Ipublic<View>.IInput_node2Element ele1 = wdcontext.createInput_node2Element();
    ele1.setAttr2("<value>");
    wdcontext.nodeInput_node2().addElement(ele);
    But this code didnt work. Model was executed without data in this case.
    So, i thought that these elements were created at view level only. And corresponding model objects were not created.
    So, I have changed code like following way:
    I have removed initialization code for Input_Node1 and Input_Node2 from view. Now, I am getting input values in two different value nodes. And before calling custom controller's method to execute model, I am making two ArrayLists and filling data in it. Now, i am passing these ArrayList objects as parameters to controller's method.
    In this method, i am setting both values as follows:
    wdcontext.currentRoot_NodeElement().modelObject().setInput_Node1(List1); 
    wdcontext.currentRoot_NodeElement().modelObject().setInput_Node2(List2); 
    Then i am executing my model.
    But, When i am setting values for Input_Node1 and Input_Node2 as shown above, values are appended instead of overwritting the value. Because of this appended values, it gives mupltiple results.
    Means, Both ways are not proper. What should be the proper and best way to pass values in this case?
    Thanks,
    Bhavik

  • ArrayList e .RangeCheck(int)line 546

    Hi guys I am working on this project
    in few word
    I have to draw different shape on a panel
    moreover when two similar shapes collide ( 2 circles ) they make a bigger circle
    when st change direction
    almost everything works
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Iterator;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel implements ActionListener {
         private static final long serialVersionUID = 1L;
         public static ArrayList <Shape>shapes;
         private javax.swing.Timer animationTmr;
         int speed;
         PlaySound audioClip = new PlaySound();
         private float heigth;
         private float width;
         private int shape1;
         private int shape2;
         public ShapePanel() {
              shapes = new ArrayList<Shape>();
              animationTmr = new javax.swing.Timer(80, this); //interval, ActionListener
              animationTmr.start();
         public ArrayList<Shape> getShapes()
              return shapes;
         public void addSquare(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Square(this,x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addCircle(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Circle(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addRectangle(int x, int y,int w,int h,  int shapeType) {
              shapes.add(new Rectangle(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addStar(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Star(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void paintComponent(Graphics g) { //called Whenever panel needs
              super.paintComponent(g); //re-displaying:
              Iterator<Shape> it = shapes.iterator(); //Iterate through Balls calling
              g.setColor(Menu.getColor());
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
              while (it.hasNext()) { //each one's paint method
                   it.next().paint(g);
         public void actionPerformed(ActionEvent ev) {      
              //On timer tick,
              Iterator<Shape> it = shapes.iterator(); //Iterate through Balls calling
              while (it.hasNext()) { //each one's updatePos() method
                   it.next().updatePos();
              checkTypeCollision();
              handleCollision();
              repaint();
        private void checkTypeCollision()
              //we iterate through all the balls, checking for collision
              for(int i=0;i<shapes.size();i++)
                   for(int j=0;j<shapes.size();j++)
                             if(i!=j)
                                  if(collide(shapes.get(i), shapes.get(j)))
                                            shape1=shapes.get(i).shapeType;
                                            shape2=shapes.get(j).shapeType;
                                             if(shape1==shape2)
                                             /*     int     newX = (int) ((shapes.get(i).getCenterX() + (shapes.get(j).getCenterX()/2))/2);
                                                  int newY = (int) ((shapes.get(i).getCenterY() + (shapes.get(j).getCenterY() /2))/2);
                                                 float newWidth =   shapes.get(i).getWidth()+(shapes.get(j).getWidth()/2);
                                                 float newHeigth = shapes.get(i).getHeigth()+(shapes.get(j).getHeigth()/2);
                                                 int newShapeType = shapes.get(i).shapeType;
                                                       if(shapes.get(i).getShapeType()==1)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            System.out.println("SIZE IS==="+     shapes.size());
                                                            System.out.println("newx====="+newX);
                                                            System.out.println("newy====="+newY);
                                                            System.out.println("newWidth====="+newWidth);
                                                            System.out.println("newx====="+newHeigth);
                                             //               shapes.add(new Rectangle(this,newX,newY,530,530,newShapeType));
                                                            System.out.println("SIZE IS==="+     shapes.size());
                                                       //     repaint();
                                                       if(shapes.get(i).getShapeType()==2)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                  //          shapes.add(new Circle(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       //     repaint();
                                                       if(shapes.get(i).getShapeType()==3)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            shapes.add(new Square(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       if(shapes.get(i).getShapeType()==3)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            //shapes.add(new Star(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       //     repaint();
         private void handleCollision()
              //we iterate through all the balls, checking for collision
              for(int i=0;i<shapes.size();i++)
                   for(int j=0;j<shapes.size();j++)
                             if(i!=j)
                                  if(collide(shapes.get(i), shapes.get(j)))
                                        shapes.get(i).hit(shapes.get(j));
                                       shapes.get(j).hit(shapes.get(i));                                   
         boolean collide(Shape b1, Shape b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //we calculate the distance between the centers two
              //colliding balls (theorem of Pythagoras)
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.shapeSize)     
                   audioClip.playRectangle();
                   return true;          
                   else return false;     
         public static int vectorSize()
              return shapes.size();
    }the drawing stops and
    i have this error after a while
    arrayList<e>.RangeCheck(int)line 546
    moreover it doesn t draw a bigger shape as i want with the line
    shapes.add(new Circle(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       help please the deadline is Tomorrow;

    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
         at java.util.ArrayList.RangeCheck(ArrayList.java:546)
         at java.util.ArrayList.get(ArrayList.java:321)
         at ShapePanel.checkTypeCollision(ShapePanel.java:156)
         at ShapePanel.actionPerformed(ShapePanel.java:77)
         at javax.swing.Timer.fireActionPerformed(Timer.java:271)
         at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    it doesn t compile because is part of a bigger project

  • Check for null and empty - Arraylist

    Hello all,
    Can anyone tell me the best procedure to check for null and empty for an arraylist in a jsp using JSTL. I'm trying something like this;
    <c:if test="${!empty sampleList}">
    </c:if>
    Help is greatly appreciated.
    Thanks,
    Greeshma...

    A null check might not be you best option.  If your requirement is you must have both the date and time component supplied in order to populate EventDate, then I would use a Script Functoid that takes data and time as parameters.
    In the C# method, first check if either is an empty string, if so return an empty string.
    If not, TryParse the data, if successful, return a valid data string for EventDate.  If not, error or return empty string, whichever satsifies the requirement.

  • Problem getting arraylist values from request

    Hi All,
    I am trying to display the results of a search request.
    In the jsp page when I add a scriplet and display the code I get the values else it returns empty as true.Any help is appreciated.
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
         <%@ include file="/includes/header.jsp"%>
         <title>Research Results</title>
    </head>
    <body>
    <div class="ui-widget  ui-widget-content">
        <%  
        ArrayList<Research> research = (ArrayList<Research>) request.getAttribute("ResearchResults");
         Iterator iterator = research.iterator();
              while(iterator.hasNext()){
              Research r = (Research) iterator.next();
              out.println("Result Here"+r.getRequesterID());
              out.println("Result Here"+r.getStatus());
        %> 
         <form>
         <c:choose>
         <c:when test='${not empty param.ResearchResults}'>
         <table cellspacing="0" cellpadding="0" id="research" class="sortable">
         <h2>RESEARCH REQUESTS</h2>
                   <tr>
                   <th><a href="#">RESEARCH ID</a></th>
                   <th><a href="#">REQUESTOR NAME</a></th>
                   <th><a href="#">DUE DATE</a></th>
                   <th><a href="#">REQUEST DATE</a></th>
                   <th><a href="#">CLIENT</a></th>
                   <th><a href="#">STATUS</a></th>
                   <th><a href="#">PRIORITY</a></th>
                   </tr>
              <c:forEach var="row" items="${param.ResearchResults}">
                        <tr title="">
                             <td id="researchID">${row.RESEARCH_ID}</td>
                             <td>${row.REQUESTER_FNAME}  ${row.REQUESTER_LNAME}</td>
                             <td><fmt:formatDate pattern="MM/dd/yyyy" value="${row.DUE_DATE}"/></td>
                             <td><fmt:formatDate pattern="MM/dd/yyyy" value="${row.CREATED_DATE}"/></td>
                             <td>${row.CLIENT}</td>
                             <td>
                             <c:choose>
                               <c:when test="${row.STATUS=='10'}">New Request</c:when>
                               <c:when test="${row.STATUS=='20'}">In Progress</c:when>
                               <c:when test="${row.STATUS=='30'}">Completed</c:when>
                              </c:choose>
                             </td>
                             <td>
                             <c:choose>
                               <c:when test="${row.PRIORITY=='3'}">Medium</c:when>
                               <c:when test="${row.PRIORITY=='2'}">High</c:when>
                               <c:when test="${row.PRIORITY=='1'}">Urgent</c:when>
                              </c:choose>
                             </td>
                             </tr>
              </c:forEach>
         </table>
         </c:when>
         <c:otherwise>
         <div class="ui-state-highlight ui-corner-all">
                   <p><b>No results Found. Please try again with a different search criteria!</b> </p>
              </div>
         </c:otherwise>
         </c:choose>
         </form>
              <%@ include file="/includes/footer.jsp"%>
         </div>
         </body>
    </html>

    What is ResearchResults?
    Is it a request parameter or is it a request attribute?
    Parameters and attributes are two different things.
    Request parameters: the values submitted from the form. Always String.
    Request attributes: objects stored into scope by your code.
    They are also accessed slightly differently in EL
    java syntax == EL syntax
    request.getParameter("myparameter") == ${param.myparameter}
    request.getAttribute("myAttribute") == ${requestScope.myAttribute}
    You are referencing the attribute in your scriptlet code, but the parameter in your JSTL/EL code.
    Which should it be?
    cheers,
    evnafets

Maybe you are looking for

  • Question - Need Advice Regarding Second Hard Drive On HP Pavilion dv7t-4100 Notebook PC

    Hi, I currently have a HP Pavilion dv7t-4100 Notebook PC, and my hard drive failed (luckily while still under warranty!).  So I contacted HP support and they are in the process of sending me a replacement hard drive, so that I may install it.  When I

  • Nokia lumia phone app cover

    what the hell going on withnokia lumias model htc had already brought the phone cover which covers on phone cover app in windowsphone 8.1  why the heell the leading wp devices manufacturer is laggy behind  bring out the phone cover app on nokia lumia

  • Display text in PRE-LOGON

    Dear members, I'd like to display some text before Forms asks for login at runtime (and then ask for a reply, with a button). I've managed to display an alert in the PRE-LOGON trigger, but the text I have to display is more than 200 characters long,

  • Envelope Mesh on a Symbol.

    I have created an envelope mesh to an object within a clipping mask and have made it into a symbol. The idea of this was to create a template where I can edit the symbol and have it automate the wrapping of the design using the envelope mesh. The pro

  • Error code 64

    hI ALL, I have read 20 - 30 threads about this error, but still i cant solve mine. Since a few days this errors pops up by accessing sharepoint over https trough tmg 2010. Who can help me, i cant fiend a solution for this weird problem. i can reach m