Declaring an ArrayList

Hi,
Being a total newbie I would like to kown how to declare an ArrayList to hold objects of a certain class?
I have a class called CraftItem how do I declare an ArrayList to hold objects of this class so I can use the methods in that class?
Thanks
Dev
BTW Why does the forum login keep asking for screen name even though I have told it the name already?

Hi,
Being a total newbie I would like to kown how to
declare an ArrayList to hold objects of a certain
class?
I have a class called CraftItem how do I declare an
ArrayList to hold objects of this class so I can use
the methods in that class?Assuming you're using at least version 5.0, where [url http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html]generics were introduced, it would look like this: List<CraftItem> list = new ArrayList<CraftItem>(); 
// ... add some elements to the list ...
for (CraftItem item : list) {
    item.someMethod();
} If you're on <= 1.4, then there's nothing built in to let you specify the type of the list's elelments. Normally you'd just use a list and cast the reference you retrieveList list = new ArrayList();
// ... call add() a few times ...
for (Iterator iter = list.iterator; iter.hasNext();) {
    CraftItem item = (CraftItem)iter.next();
    item.someMethod();

Similar Messages

  • Declaring Arraylist

    in my application i want to manage just 1 arraylist i have 2 objects CD DVD i want to put all the values from those objects into 1 arraylist
    here my arraylist declared in my itemcontroller class
    private ArrayList<Item> items = new ArrayList<Item>();
    each time i call my addItemCD and addItemDVD methods in my itemcontroller class
    the arraylist size items.size()
    seems to be stuck printin 1 every time, why aint it incrementin up every time i add a item..
    even when i take away new key word from arraylist() eclipse throws error stops runing application...
    any help much appreciated
    cheers
    package stage03;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    import stage02.CD;
    import stage02.DVD;
    import stage02.Item;
    public class ItemController {
         private ArrayList<Item> items = new ArrayList<Item>();  // has a item collection
         public String title;
         public int time;
         public double price;
         public String comment;
         public String artist;
         public int track;
         public String dvdTitle;
         public int dvdTime;
         public String dvdComent;
         public Double dvdPrice;
         public String director;
         public String rate;
         public void addItemCD(String title, int time,double price, String comment,String artist,int track ){
              this.title = title;
              this.time = time;
              this.price = price;
              this.comment = comment;
              this.artist = artist;
              this.track = track;
              CD cd01 = new CD(null,0,0,null,null,0);
              cd01.setItemTitle(title);
              cd01.setItemPlayTime(time);
              cd01.setItemPrice(price);
              cd01.setItemComments(comment);
              cd01.setArtist(artist);
              cd01.setTrack(track);
              this.items.add(cd01);
              for (int i = 0; i < items.size(); i++){
              System.out.println(items.get(i));
              System.out.println(items.size());
    }

    georgemc wrote:
    Yucca wrote:
    @ the op...
    Declaring an arraylist as type <item> is not gonna score you good points in future maintenance of your code. Java should be strongly typed and if you are giving
    classes/objects the name of Item then you are headed for trouble. Some more meaningful names like PhoneBookEntry, PrivateContractor, LibraryBook etc. are what you should be aiming at.
    In case you want to know why... a simple explanation is that it makes it easier for you to work with your own code and maintain code when the compiler starts throwing errors that point your to your class.
    >@ the op...
    Declaring an arraylist as type <item> is not gonna score you good points in future maintenance of your code. Java should be strongly typed and if you are giving
    classes/objects the name of Item then you are headed for trouble. Some more meaningful names like PhoneBookEntry, PrivateContractor, LibraryBook etc. are what you should be aiming at.
    In case you want to know why... a simple explanation is that it makes it easier for you to work with your own code and maintain code when the compiler starts throwing errors that point your to your class.Depends entirely on context. In the context of, say, a shopping cart, Item is a very obvious abstraction for both CD and DVD
    Then my statement still stands. Surely ShoppingCartItem is more descriptive than Item. Are we talking about a office item of a shopping cart item or a household item? I am just saying that the earlier one decides to give classes meaningful names the better. And whats they point of a type-safe list if I can go stuff my items that are not for sale in your list of shopping cart items?

  • Passing arraylist between constructors?

    Hi guys,
    I've pretty new to java, and I think i'm having a little trouble
    understanding scope. The program I'm working on is building a jtree
    from an xml file, to do this an arraylist (xmlText) is being built and
    declared in the function Main. It's then called to an overloaded
    constructor which processes the XML into a jtree:
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    Later, in the second constructor which builds my GUI, I try and call
    the same arraylist so I can parse this XML into a set of combo boxes,
    but get an error thrown up at me that i'm having a hard time solving- :
    public Editor( String title ) throws ParserConfigurationException
    // additional code
    // Create a read-only combobox- where I get an error.
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    This is the way I understand the Arraylist can be converted to a string
    to use in the combo boxs. However I get an error thrown up at me here
    at about line 206, which as far as I understand, is because when the
    overloaded constructor calls the other constructor:
    public Editor( String title ) throws ParserConfigurationException -
    It does not pass in the variable xmlText.
    I'm told that the compiler complains because xmlText is not defined
    at that point:
    - it is not a global variable or class member
    - it has not been passed into the function
    and
    - it has not been declared inside the current function
    Can anyone think of a solution to this problem? As I say a lot of this
    stuff is still fairly beyond me, I understand the principles behind the
    language and the problem, but the solution has been evading me so far.
    If anyone could give me any help or a solution here I'd be very
    grateful- I'm getting totally stressed over this.
    The code I'm working on is below, I've highlighted where the error
    crops up too- it's about line 200-206 area. Sorry for the length, I was
    unsure as to how much of the code I should post.
    public class Editor extends JFrame implements ActionListener
    // This is the XMLTree object which displays the XML in a JTree
    private XMLTree XMLTree;
    private JTextArea textArea, textArea2, textArea3;
    // One JScrollPane is the container for the JTree, the other is for
    the textArea
    private JScrollPane jScroll, jScrollRt, jScrollUp,
    jScrollBelow;
    private JSplitPane splitPane, splitPane2;
    private JPanel panel;
    // This JButton handles the tree Refresh feature
    private JButton refreshButton;
    // This Listener allows the frame's close button to work properly
    private WindowListener winClosing;
    private JSplitPane splitpane3;
    // Menu Objects
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem newItem, openItem, saveItem,
    exitItem;
    // This JDialog object will be used to allow the user to cancel an exit
    command
    private JDialog verifyDialog;
    // These JLabel objects will be used to display the error messages
    private JLabel question;
    // These JButtons are used with the verifyDialog object
    private JButton okButton, cancelButton;
    private JComboBox testBox;
    // These two constants set the width and height of the frame
    private static final int FRAME_WIDTH = 600;
    private static final int FRAME_HEIGHT = 450;
    * This constructor passes the graphical construction off to the
    overloaded constructor
    * and then handles the processing of the XML text
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    this( title );
    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
    for ( int i = 1; i < xmlText.size(); i++ )
    textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    System.out.println( message );
    }//end try/catch
    } //end Editor( String title, String xml )
    * This constructor builds a frame containing a JSplitPane, which in
    turn contains two
    JScrollPanes.
    * One of the panes contains an XMLTree object and the other contains
    a JTextArea object.
    public Editor( String title ) throws ParserConfigurationException
    // This builds the JFrame portion of the object
    super( title );
    Toolkit toolkit;
    Dimension dim, minimumSize;
    int screenHeight, screenWidth;
    // Initialize basic layout properties
    setBackground( Color.lightGray );
    getContentPane().setLayout( new BorderLayout() );
    // Set the frame's display to be WIDTH x HEIGHT in the middle of
    the screen
    toolkit = Toolkit.getDefaultToolkit();
    dim = toolkit.getScreenSize();
    screenHeight = dim.height;
    screenWidth = dim.width;
    setBounds( (screenWidth-FRAME_WIDTH)/2,
    (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
    FRAME_HEIGHT );
    // Build the Menu
    // Build the verify dialog
    // Set the Default Close Operation
    // Create the refresh button object
    // Add the button to the frame
    // Create two JScrollPane objects
    jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();
    // First, create the JTextArea:
    // Create the JTextArea and add it to the right hand JScroll
    textArea = new JTextArea( 200,150 );
    jScrollRt.getViewport().add( textArea );
    // Next, create the XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree to
    be editable
    XMLTree.setEditable( false );
    // Wrap the JTree in a JScroll so that we can scroll it in the
    JSplitPane.
    jScroll.getViewport().add( XMLTree );
    // Create the JSplitPane and add the two JScroll objects
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
    jScrollRt );
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(200);
    jScrollUp = new JScrollPane();
    jScrollBelow=new JScrollPane();
    // Here is were the error is coming up
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    * I'm adding the scroll pane to the split pane,
    * a panel to the top of the split pane, and some uneditible
    combo boxes
    * to them. Then I'll rearrange them to rearrange them, but
    unfortunately am getting an error thrown up above.
    panel = new JPanel();
    panel.add(queryBox);
    panel.add(queryBox2);
    panel.add(queryBox3);
    panel.add(queryBox4);
    panel.add(queryBox5);
    jScrollUp.getViewport().add( panel );
    // Now building a text area
    textArea3 = new JTextArea(200, 150);
    jScrollBelow.getViewport().add( textArea3 );
    splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    jScrollUp, jScrollBelow);
    splitPane2.setPreferredSize( new Dimension(300, 200) );
    splitPane2.setDividerLocation(100);
    splitPane2.setOneTouchExpandable(true);
    // in here can change the contents of the split pane
    getContentPane().add(splitPane2,BorderLayout.SOUTH);
    // Provide minimum sizes for the two components in the split pane
    minimumSize = new Dimension(200, 150);
    jScroll.setMinimumSize( minimumSize );
    jScrollRt.setMinimumSize( minimumSize );
    // Provide a preferred size for the split pane
    splitPane.setPreferredSize( new Dimension(400, 300) );
    // Add the split pane to the frame
    getContentPane().add( splitPane, BorderLayout.CENTER );
    //Put the final touches to the JFrame object
    validate();
    setVisible(true);
    // Add a WindowListener so that we can close the window
    winClosing = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    verifyDialog.show();
    addWindowListener(winClosing);
    } //end Editor()
    * When a user event occurs, this method is called. If the action
    performed was a click
    * of the "Refresh" button, then the XMLTree object is updated using
    the current XML text
    * contained in the JTextArea
    public void actionPerformed( ActionEvent ae )
    if ( ae.getActionCommand().equals( "Refresh" ) )
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    else if ( ae.getActionCommand().equals( "OK" ) )
    exit();
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    verifyDialog.hide();
    }//end if/else if
    } //end actionPerformed()
    // Program execution begins here. An XML file (*.xml) must be passed
    into the method
    public static void main( String[] args )
    String fileName = "";
    BufferedReader reader;
    String line;
    ArrayList xmlText = null;
    Editor Editor;
    // Build a Document object based on the specified XML file
    try
    if( args.length > 0 )
    fileName = args[0];
    if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
    ".xml" ) )
    reader = new BufferedReader( new FileReader( fileName )
    xmlText = new ArrayList();
    while ( ( line = reader.readLine() ) != null )
    xmlText.add( line );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    // Construct the GUI components and pass a reference to
    the XML root node
    Editor = new Editor( "Editor 1.0", xmlText );
    else
    help();
    } //end if ( fileName.substring( fileName.indexOf( '.' )
    ).equals( ".xml" ) )
    else
    Editor = new Editor( "Editor 1.0" );
    } //end if( args.length > 0 )
    catch( FileNotFoundException fnfEx )
    System.out.println( fileName + " was not found." );
    exit();
    catch( Exception ex )
    ex.printStackTrace();
    exit();
    }// end try/catch
    }// end main()
    // A common source of operating instructions
    private static void help()
    System.out.println( "\nUsage: java Editor filename.xml" );
    System.exit(0);
    } //end help()
    // A common point of exit
    public static void exit()
    System.out.println( "\nThank you for using Editor 1.0" );
    System.exit(0);
    } //end exit()
    class newMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    textArea.setText( "" );
    try
    // Next, create a new XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION );
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree
    to be editable
    XMLTree.setEditable( false );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    }//end actionPerformed()
    }//end class newMenuHandler
    class openMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    openMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = openItem.getParent();
    }//end openMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'open'
    choice = jfc.showOpenDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName, line;
    BufferedReader reader;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    reader = new BufferedReader( new FileReader( fileName ) );
    textArea.setText( reader.readLine() + "\n" );
    while ( ( line = reader.readLine() ) != null )
    textArea.append( line + "\n" );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    XMLTree.refresh( textArea.getText() );
    catch ( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class openMenuHandler
    class saveMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    saveMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = saveItem.getParent();
    }//end saveMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'save'
    choice = jfc.showSaveDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName;
    File fObj;
    FileWriter writer;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    writer = new FileWriter( fileName );
    textArea.write( writer );
    // The file will have to be re-read when the Document
    object is parsed
    writer.close();
    catch ( IOException ioe )
    ioe.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class saveMenuHandler
    class exitMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    verifyDialog.show();
    }//end actionPerformed()
    }//end class exitMenuHandler
    class XmlFileFilter extends javax.swing.filechooser.FileFilter
    public boolean accept( File fobj )
    if ( fobj.isDirectory() )
    return true;
    else
    return fobj.getName().endsWith( ".xml" );
    }//end accept()
    public String getDescription()
    return "*.xml";
    }//end getDescription()
    }//end class XmlFileFilter
    } //end class Editor
    Sorry if this post has been a bit lengthy, any help you guys could give
    me solving this would be really appreciated.
    Thanks,
    Iain.

    Hey. Couple pointers:
    When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
    Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
    That way people don't have to wade through irrelevant stuff and
    they have an easier time helping.
    http://homepage1.nifty.com/algafield/sscce.html
    As for your problem, this is a scope issue. You declare an
    ArrayList xmlText in main(). That means that everywhere after
    the declaration in main(), you can reference your xmlText.
    So far so good. Then, inside main(), you call
    Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
    Editor(String title, ArrayList xmlText) [which happens to be a
    constructor, but that's not important]. When you do that, you
    make the two variables title and xmlText available to the whole
    Editor(String, ArrayList) method.
    This is where you get messed up. You invoke another method
    from inside Editor(String, ArrayList). When you call
    this(title);you're invoking the method Editor(String title). You aren't passing
    in your arraylist, though. You've got code in the Editor(String) method
    which is trying to reference xmlText, but you'd need to pass in
    your ArrayList in order to do so.
    My suggestion would be to merge the two constructor methods into
    one, Editor(String title, ArrayList xmlText).

  • Displaying Arraylist in label

    Jo, i want to display my list in a label on an actionevent, i want to have each item on a new line. This is how far i got. Can somebody help plz
    i declared my arraylist btas in my public class
    public void jTextField1_actionPerformed(ActionEvent e) {
    btas.add(jTextField1.getText());
    int aantal = btas.size();
    display();
    public void display(){
    String next= "\n";
    jLabel1.setText("");
    for (int i=0; i<btas.size();i++) jLabel1.setText(next+btas);

    \n won't work - HTML will. You could use something likeStringBuilder builder = new StringBuilder ();
    for (Object element: list) { // or whatever's the type of your list
        if (builder.length () > 0) {
            builder.append ("<br>");
        builder.append (String.valueOf (element));
    label.setText (String.format("<html>%s</html>", builder.toString ());

  • A bunch of ArrayLists

    Overview
    My program needs to store 11 different types of data (numbered 1 through 12, skipping 5, although I may find a way to fill this gap soon). Each type of data needs to have a bunch of entries of undeterminate size (ArrayList), but I know there will always be 11 different types of data. I figured instead of having 11 different ArrayList variables and 11 getters, 11 setters, and 11 removers, I could just store them all in an array of some sort, and then only have 1 getter/setter/remover/etc which takes an argument of what data type it is.
    Problem
    Problem is, I'm not exactly sure what to use to group these ArrayLists together. I tried an array, but it complains about the generic typing:
    ArrayList<Resource> resList[] = new ArrayList<Resource>[13]();
    or any combination/order of [13] and () and it always complains "Cannot create a generic array of ArrayList<Resource> or "Cannot convert from ArrayList<Resource> to ArrayList<Resource>[]"
    Solution
    Using basic google skills, I discovered I could use:
    ArrayList resList[] = new ArrayList[12];
    essentially just dropping the type...
    and then loop through the 13 new ArrayList<Resource>();
    Resulting Problem
    Then when I go to add one of the datatypes to its respective data type ArrayList
    resList[Resource.PATH].add(new Path());
    it warns me: "...Type Safety... raw type ArrayList... should be Parameterized"
    it also says the same thing, somewhat surprisingly, when I generalize the path data type back down to Resource:
    resList[Resource.PATH].add((Resource)new Path());
    since I did declare each arraylist of type <Resource>. Yet it makes the same complaint.
    Conclusion
    There's basically 4 possible outcomes to this that I can think up.
    1) (Mostly desirable) There is a solution to my Type Safety warning.
    2) (Undesirable) use @SuppressWarnings
    3) An alternative to bunching them in arrays (I had a glance at Arrays.asList, but wasn't so sure about it)
    4) (Undesirable) just leave them as 11 different ArrayList variables and make them public.
    Thanks in advance,
    -IsmAvatar

    @musicalscale, thanks, I think. Is this just creating
    an ArrayList of ArrayLists? Because I don't think
    that's appropriate here because the 11 data types are
    unchanging (until I fill in the gap at 5, in which
    case it's simply a matter of slight recoding which
    I'm more than happy to do).Yes, it's an ArrayList of ArrayLists. It will get rid of the generics warnings. If you don't plan on changing the size of the outer ArrayList, then you don't have to change it. Only your one class that keeps the private ArrayList of ArrayLists will have direct access to the outer list (unless you code it otherwise). So, you don't have to worry that someone else will mess up the list.
    Or, after you create the initial list of lists, store the private reference as an unmodifiable List:
    private final List< List < Resource > > resList;// In your constructor (or another method):
    // create tempResList with generics as described,
    // then set the instance variable as
    resList = Collections.unmodifiableList(tempResList);Then even your local class can't add or remove things from the outer list (they can still modify the inner lists).
    As for HashMap, I guess it doesn't matter that the
    order may change, since we have the key paired with
    it. But is HashMap also dynamically resizable? Maybe
    I'm just blind to the internal workings.Yes, a HashMap is dynamically resizable. Since you have a key, yes, the order doesn't matter (there is also a TreeMap that keeps the keys sorted, but you don't really need that for your stated purposes). You can make an unmodifiable Map similar to how you make an unmodifiable List.

  • Problem with remove() method of ArrayList collection

    Dear All,
    I have a program below: See the statement in bold
    //Start of the Program
    import java.util.*;
    public class ArrayListTest
         public static void main(String args[])
              //declare an arraylist of type String
              List<String> stringStorage = new ArrayList<String>();
              //add elements to the ArrayList
              stringStorage.add("apple");
              stringStorage.add("banana");
              stringStorage.add("papaya");
              stringStorage.add("peach");
              stringStorage.add("cucumber");
              stringStorage.add("orange");
              stringStorage.add("grapes");
              stringStorage.add("plum");
              stringStorage.add("chiku");
              stringStorage.add("pomegrenate");
              stringStorage.add("pomegrenate2");
              //iterate through the ArrayList
              Iterator<String> iterate = stringStorage.iterator();
              //test whether an element is present
              boolean isPresent = stringStorage.contains("xxx");
              System.out.println("xxx is Present "+isPresent);
              //remove an element from the ArrayList
    Line no: 12     System.out.println("Remove apple:(true/false)"+stringStorage.remove("apple"));
              Loop:
              for (int i=0;i<stringStorage.size();i++)
                   while (iterate.hasNext()==true)
                        System.out.println("Element in the arraylist["+i+"] "+iterate.next());
                        //iterate.remove();
                        continue Loop;
    End of Outer Loop:
    //End of the Program
    It compiles fine. But when I try to run , it gives a unchecked exception in main ConcurrentModificationException.
    Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
    at java.util.AbstractList$Itr.next(Unknown Source)
    at ArrayListTest.main(ArrayListTest.java:48)
    But, if I remove Line no 12(in bold), or put the same statement after End of Outer Loop: , I do not get the error. Can you explain this phenomenon?

    look what you do:
    1/ you retrieve the iterator
    2/ you remove apple
    3/ you browse the iterator
    but actually, the iterator kept a reference to the "apple" you just removed ; that s why it gets screwed ;
    you mustn't operate on the list if you re not over with the iterator work

  • How do I transfer from one ArrayList to another -

    Hi
    Basically what I want to do is transfer from one arayList to another using an iterator to iterate of the list and transfer certain entries to another - one is called lots, the other is called unsold.
    I don't want help with trying to get the right fields to transfer at the moment I'm just trying to get it to transfer EVERY entry, which I cant seem to to with this while loop
    public ArrayList getUnsold()
           Iterator it = lots.iterator();
            while(it.hasNext()) {
                    Lot lot = (Lot) it.next();
                    unsold.add(lot.getDescription());
                    return unsold;With the above all I seem to get is the first item in the 'lots' list to transfer even though theree are 3 items that need to be transferred...
    I have declared all arraylists and everything on this level works I just cant transfer items over properly...
    Any help is most appreciated.
    -greg

    Add these print statements (and others you think might help) to help you see what's going on: public ArrayList getUnsold()
           Iterator it = lots.iterator();
            while(it.hasNext()) {
                    Lot lot = (Lot) it.next();
                    System.out.println(lot);
                    System.out.println(lot.getDescription)());
                    unsold.add(lot.getDescription());
                    System.out.println(unsold);

  • How to pass java arraylist into javascript arrays

    Hi, i have declare an arraylist
    ArrayList list1 = new ArrayList();Inside the arraylist, there are elements. Now, i wan to pass the elements in the java arraylist into javascript arrays but i encounter javascript errors.
    This is how i code.
    var arr1 = new Array();
    <%
    for ( int x =0; x<list1.size(); x++)
    %>
         arr1[<%=x%>] = <%=(String)list1.get(x)%>;
    <%
    %>how do i solve this problem?
    Thanks for the guidance in advance

    JTech wrote:
    Hi,
    Use Quotes around string value ( arr1[indexposition] = "stringvalue";), when assign to javascript array as below.
    arr1[<%=x%>] = "<%=(String)list1.get(x)%>"; Regards,
    Ram.Hi Ram,
    How about using arr1 = <%=list.toArray()%> ??? Is this possible? I tried it but was not working on my IDE. Do you have any solutions for this??
    Regards,
    Thiagu

  • How to change elements in ArrayList into String

    Greetings,
    i like to change elements in arrayList into string.
    This is how i declare an ArrayList in a Java file
    ArrayList listing = new ArrayList();below is just a simple example of how i insert the string into the arraylist
    String concat = "';
    concat = concat + "apple";
    //Transfer the concat string into arraylist
    listing.add(concat);
    return listing;
    {code}
    On my Jsp page, it will receive the ArrayList from the java file. Lets say the Arrayist is pass into my JSP arraylist
    This is my JSP arraylist
    {code}ArrayList optLists = new ArrayList();{code}
    Inside the arraylist element, it holds data eg: *308577;;RS | [CAT 2] Level: Arena, Section: A02* with a pipe between RS and CAT 2.
    Now i looping the arraylist
    {code}int a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              splitTemp =  tempString.split("|");
              System.out.println("Split String Results: "+ splitTemp);
         {code}}
    Heres the error:
    *SeatAvailable_jsp.java:560: incompatible types*
        *[javac] found   : java.lang.String[]*
        *[javac] required: java.lang.String*
        *[javac]             splitTemp =  tempString.split("|");*
        *[javac]*       
    What can i do to solve the problem?
    Edited by: leeChaolan on May 2, 2008 4:45 AM
    Edited by: leeChaolan on May 2, 2008 4:48 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    paternostro is right, you are returning an array into a string which is wrong
    but try this, i haven't tested it though..
    nt a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              String[] splitTemp =  tempString.split("|");
              for(String xyz : splitTemp)
                   System.out.println("Split String Results: "+ xyz);
         }Edited by: linker on May 2, 2008 1:17 PM
    Edited by: linker on May 2, 2008 1:18 PM

  • Is it a better practice to create an ArrayList at class level?

    Hello forum members,
    Of late one of my collegue suggested me to declare an ArrayList at class level and clearing the data for each method call as garbage collection is not guaranted in java and we may end-up with large pool of ArrayList objects on subsequent method calls!!!
    FYI :There was a need of an ArrayList object for a single method only.

    Bad suggestion. Variables should be declared in the scope in which they are used.
    Also bad reasoning. It needn't bother the programmer that garbage collection isn't guaranteed to run whenever a variable goes out of scope. It's sufficient that it is guaranteed to run before the program throws a OutOfMemoryError.
    That said, parts of the JDK instantiate an object as a class field and set (and subsequently access) its attributes in various methods to reduce the overhead of object creation for enhancing performance. Much of this is legacy code from the days of slower computers and less efficient JVMs and probably wouldn't be written the same way today.
    db

  • Help needed on accessing an arraylist

    Hello
    I have declared an arrayList globally as follows:
         ArrayList itemList = new ArrayList();I have then wrote a method to test if a user's session is new, if so set the arrayList into the session using setAttribute. The code then gets the attribute from the session and stores it in the variable listFromSession. This is also set into the session. The code is below:
    //ItemList itemList;
              if (ca.isNew()){
                   //itemList = new ArrayList();
              ca.setAttribute("itemlist", itemList);
              ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
              listFromSession.add(c);
              ca.setAttribute("itemList", listFromSession);I have then tried to retrieve elements from the arrayList. Code is below, but im not sure if im trying to access the arrayList as you would a normal array:
    ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
                        for (int i = 0; i < listFromSession.length; i++){
                             int amt = listFromSession.getprodQuant(i);
                             int id = listFromSession.getStockID(i);
                             String name = listFromSession.getprodName(i);
                             float price = listFromSession.getprodPrice(i);
                             float totalPrice = amt * price;
                             out.println("<TD>" + id + "</TD>");
                             out.println("<TD>" + name + "</TD>");
                             out.println("<TD>" + amt + "</TD>");
                             out.println("<TD>" + price + "</TD>");
                             out.println("<TD>" + totalprice + "</TD>");
                        }For example, i did originally have int amt = listFromSession(i).getprodQaunt; and so forth but that threw the same error: cannot find symbol getProdQuant even when I put code it in the example above.
    Basically the compiler cannot find the get methods nor the variable length(), ive tried size() but it dosn't like that either
    Can anyone help?
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Can anyone understand as to why my arraylist cannot be accesssed or return the elements?
    Is it because the initialization is outside of the method that is accessing the list?
    package cart;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Enumeration;
    import cart.CartItem;
    public class CartSession extends HttpServlet
         private HttpSession ca = null;
         private int numProducts = 0;
         ArrayList itemList = new ArrayList();
         ArrayList listFromSession = new ArrayList();
           public void doPost(HttpServletRequest request,
                                   HttpServletResponse response)
                throws ServletException, IOException
             response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              int currentProduct = Integer.parseInt(request.getParameter("stock"));
              String currentName = request.getParameter("name");
              float currentPrice = Float.parseFloat(request.getParameter("price"));
              String am = request.getParameter("Amount");
              if (am == null) am = "1";
              int currentAmount = Integer.parseInt(am);
              cart.CartItem c = new cart.CartItem(currentProduct, currentName, currentPrice, currentAmount);
              ca = request.getSession();
              //ItemList itemList;
              if (ca.isNew()){
                   //itemList = new ArrayList();
              ca.setAttribute("itemlist", itemList);
              ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
              listFromSession.add(c);
              ca.setAttribute("itemList", listFromSession);
              ca.setAttribute("currentProd", c);
              sendPage(response);
         private void sendPage(HttpServletResponse reply) throws IOException
                        reply.setContentType("text/HTML");
                        PrintWriter out = reply.getWriter();
                        out.println("<HTML>");
                        out.println("<HEAD>");
                        out.println("<TITLE></TITLE>");
                        out.println("<HEAD>");
                        out.println("<BODY><H1>Your Shopping Cart</H1>");
                        out.println("<CENTER>");
                        out.println("<BR><BR><BR>");
                        //cart.removeAttribute("currentProd");
                             out.println("<TABLE BGCOLOR=Aqua BORDER=2>");
                             out.println("<TR>");
                             out.println("<TH>Stock ID</TH>");
                             out.println("<TH>Product</TH>");
                             out.println("<TH>Quantity</TH>");
                             out.println("<TH>Unit price</TH>");
                             out.println("<TH>Total price</TH>");
                             out.println("</TR>");
                        ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
                        for (int i = 0; i < listFromSession.length; i++){
                             int amt = listFromSession.getprodQuant(i);
                             int id = listFromSession.getStockID(i);
                             String name = listFromSession.getprodName(i);
                             float price = listFromSession.getprodPrice(i);
                             float totalPrice = amt * price;
                             out.println("<TD>" + id + "</TD>");
                             out.println("<TD>" + name + "</TD>");
                             out.println("<TD>" + amt + "</TD>");
                             out.println("<TD>" + price + "</TD>");
                             out.println("<TD>" + totalprice + "</TD>");
                             //See if user wants more items
                             out.println("<FORM METHOD=POST ACTION='paymentform.html'>");
                             out.println("Would you like to<BR>");
                             out.println("<INPUT TYPE=SUBMIT VALUE=\" Add more items \">");
                             out.println("<FORM METHOD=POST ACTION='paymentform.html' \">");
                             out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
                        out.println("</TABLE>");
                        out.println("</FORM>");
                        out.println("</CENTER>");
                        out.println("</BODY>");
                        out.println("</HTML>");
                        out.flush();
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help needed with arraylists

    I am trying to do the following:
    Class Polygon, which takes as parameter a set of Point objects (passed to it by means of an ArrayList of Point objects), and has a method for displaying the polygon on a canvas (the polygon need not be closed, i.e. its first and last points need not have the same coordinates; the canvas may be passed to the class or to the method).
    I have the following code:
    Point.java:
    * Point.java
    * Defines the base class for the drawing exercises
    package csc812;
    import drawing.*;
    class Point
    private int m_iXValue;
    private int m_iYValue;
    // Default constructor
    public Point()
    this.m_iXValue = 0;
    this.m_iYValue = 0;
    // values constructor
    public Point(int x,int y)
    this.m_iXValue = x;
    this.m_iYValue = y;
    // Copy constructor
    public Point(Point P)
    this.m_iXValue = P.m_iXValue;
    this.m_iYValue = P.m_iYValue;
    // Calculates the distance between this and a given point
    public double distance(Point p)
    return Math.sqrt((m_iXValue-p.m_iXValue)*(m_iXValue-p.m_iXValue) +
    (m_iYValue-p.m_iYValue)*(m_iYValue-p.m_iYValue));
    // Draws a line between this and the given point
    public void DrawLine(Point p,Canvas c)
    c.drawLine(m_iXValue,m_iYValue,p.m_iXValue,p.m_iYValue);
    // Outputs the coordinates - primarily for debugging
    public void dump()
    System.out.println("(" + m_iXValue + "," + m_iYValue + ")");
    Polygon.java:
    * Polygon.java
    * This class uses the Point class to draw a polygon based on the
    given points
    * One critical assumption we make is that element 0 of the array list
    is the
    * starting point of the drawing
    package csc812;
    import java.lang.*;
    import java.util.*;
    import java.awt.Color;
    import drawing.*;
    import csc812.Point;
    class Polygon extends Point
    // Declare an ArrayList, since we cannot predetermine how many
    elements we will have
    private ArrayList m_List;
    // foreground colour is part of the polygon
    private Color m_ForeColour;
    // Default constructor
    public Polygon()
    m_List = new ArrayList();
    m_ForeColour = Color.BLACK;
    // Constructor
    public Polygon(ArrayList List,Color cl)
    if (List.contains(Point))
    m_List = new ArrayList();
    m_List = List;
    else
    System.out.println("Polygon constructor error");
    System.out.println("The ArrayList passed is not of type Point, so
    cannot construct object");
    m_ForeColour = cl;
    // Copy constructor
    public Polygon(Polygon p)
    m_List = new ArrayList();
    m_List = p.m_List;
    m_ForeColour = p.m_ForeColour;
    // Draws the polygon
    public void Display(Canvas c)
    // Declare array for use
    Point [] pArray = new Point[m_List.size()];
    pArray = m_List.toArray();
    c.setForegroundColor(m_ForeColour);
    for (int i = 0;i < pArray.length;i++)
    try
    Point p1 = new Point(pArray);
    Point p2 = new Point(pArray[i+1]);
    p1.DrawLine(p2,g);
    catch(ArrayIndexOutOfBoundsException e)
    break;
    // Sets foreground colour
    public void SetColour(Color f)
    m_ForeColour = f;
    // Output for debugging
    public void Dump()
    // Declare array for use
    Point [] pArray = new Point[m_List.size()];
    pArray = m_List.toArray();
    for (int i = 0;i < pArray.length;i++)
    Point p = new Point(pArray[i]);
    p.Dump();
    I can't seem to get this to work, I think I'm close to being correct but can anyone help me get it right?
    Thanks,
    Andy

    In general, you should not name an object the same name as a class. List is an interface in package java.util. So, you should name your ArrayList something like myList, or aList, or theStupidFarkingList. And when you call a method, you must match the type of object you are passing in (the argument) to the type declared in the method (the parameter).
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Follow Up to Scanner Input from File

    Alright, I have another problem. My code is this:
    for (int j = 0; j < username.length; j++) {
         String line = input.nextLine();          // Create a temporary String that will store each line
         // Check if the temporary line isn't empty
         if (line.length() > 1) {
                 numAccounts++;
                 username[j] = line.substring(10);
                 password[j] = input.nextLine().substring(10);
                 System.out.println(username[j]);
         } else {     // If the temporary line is empty, go back on the loop to prevent empty array entries
                  j--; }
         }It runs through once, and then stops. Here are the declarations:
    static int numAccounts = 1;
    static String[] username = new String[numAccounts];
    static String[] password = new String[numAccounts];
    static  Scanner input = new Scanner(new BufferedReader(new FileReader("account.txt")));Which was done outside of the main method.
    Why does the loop iterate only once?

    Woah, don't need to get all heated up about something I'm doing wrong. I'm just trying to figure this out. Sorry if I'm getting on your nerves.
    So anyways, I did the ArrayList method with your suggestion of making it an ArrayList of Objects. This is what I have so far:
    // Declare the ArrayList that will store all the Account Objects retrieved from the database
    static ArrayList<Account> accounts = new ArrayList<Account>();
    while (input.hasNextLine()) {
        String line = input.nextLine();          // Create a temporary String that will store each line
        // Check if the temporary line isn't empty
        if (line.length() > 0) {
             //System.out.println(line);
             String currentName = line.substring(10);
             String currentPass = input.nextLine().substring(10);
             Account current = new Account(currentName, currentPass);
             accounts.add(current);
    }Yes, I stuck with using the line.length() > 0, because trying to use line != null doesn't work properly for me. Not entirely sure why. Just throws IndexOutOfBoundsException when it's called.
    And my Account Object class is as so:
    class Account {
         static String username, password;
         Account(String username, String password) {
              this.username = username;
              this.password = password; }
    }I tried to print out the username and passwords to the indexes of 0, 1, and 2, and they're all the same.
    System.out.println(accounts.get(0).username);
    System.out.println(accounts.get(0).password);
    System.out.println(accounts.get(1).username);
    System.out.println(accounts.get(1).password);
    System.out.println(accounts.get(2).username);
    System.out.println(accounts.get(2).password);What is also interesting, is that it only fetched (or copied) the last two lines in the text document. It ignores all the entries before that.
    Do you know what I did wrong? I think I did a logic error in there somewhere.

  • How to retrieve value from xml file

    hi all,
    can somebody pls tell me how to retrieve value from xml file using SAXParser.
    I want to retrieve value of only one tag and have to perform some validation with that value.
    it's urgent .
    pls help me out
    thnx in adv.
    ritu

    hi shanu,
    the pbm is solved, now i m able to access XXX no. in action class & i m able to validate it. The only thing which i want to know is it ok to declare static ArrayList as i have done in this code. i mean will it affect the performance or functionality of the system.
    pls have a look at the following code snippet.
    public class XMLValidator {
    static ArrayList strXXX = new ArrayList();
    public void validate(){
    factory.setValidating(true);
    parser = factory.newSAXParser();
    //all factory code is here only
    parser.parse(xmlURI, new XMLErrorHandler());     
    public void setXXX(String pstrXXX){          
    strUpn.add(pstrXXX);
    public ArrayList getXXX(){
    return strXXX;
    class XMLErrorHandler extends DefaultHandler {
    String tagName = "";
    String tagValue = "";
    String applicationRefNo = "";
    String XXXValue ="";
    String XXXNo = "";          
    XMLValidator objXmlValidator = new XMLValidator();
    public void startElement(String uri, String name, String qName, Attributes atts) {
    tagName = qName;
    public void characters(char ch[], int start, int length) {
    if ("Reference".equals(tagName)) {
    tagValue = new String(ch, start, length).trim();
    if (tagValue.length() > 0) {
    RefNo = new String(ch, start, length);
    if ("XXX".equals(tagName)) {
    XXXValue = new String(ch, start, length).trim();
    if (XXXValue.length() > 0) {
    XXXNo = new String(ch, start, length);
    public void endElement(String uri, String localName, String qName) throws SAXException {                    
    if(qName.equalsIgnoreCase("XXX")) {     
    objXmlValidator.setXXX(XXXNo);
    thnx & Regards,
    ritu

  • How to find the ocuurence of a word from LIST A in LIST B in a text file?

    Hey if you look at the text file there is LIST A and LIST B.. i need to find the ocuurence of a word from LIST A in LIST B. Eg: if my output is (1,3)
    then first word from LIST A occurs in 3 places in LIST B.
    Can you please get the sample code to do this process.
    Please let me know..
    My text file looks like this below :
    phrases.txt
    LIST A
    aamsz
    abaffiliate
    aboard casino
    above computer
    above pop
    above violat
    LIST B
    http://209.153.231.131
    HTTP/1.0 200 OK
    Server: Microsoft-IIS/5.0
    Date: Mon, 02 Feb 2004 11:53:26 GMT
    IISExport: This web site was exported using IIS Export v2.2
    IISExport: This web site was exported using IIS Export v2.2
    Content-Length: 274
    Content-Type: text/html
    Set-Cookie: ASPSESSIONIDSSDBBBAR=OOGFKOJBMKMDCGPIHPADALHB; path=/
    aboard casino
    Cache-control: private
    abaffiliate
    above computer

    The key difference is that Vector is synchronized whilst ArrayList is not. Synchronized means that the classes methods can safely be accessed by different threads and as your application will not be multithreaded then the ArrayList is possibly the better option.
    To store Strings in an ArrayList, you first need to declare the ArrayList object something like this;
    ArrayList<String> listAList = new ArrayList<String>();and you would obviously do something similar for the ArrayList that will hold the Strings that should belong to List B.
    The first thing to note is that you can use the new (well new in version 1.5 anyway) generics techniques to specify the type of the object the ArrayList will hold; Strings in this case.
    To add a value into the ArrayList once you have read it from the file and decided if it belongs in the List A or List B ArrayList, all you need to do is call the add() method of the ArrayList something like this;
    // Assume that you read the line from the file into a variable called temp;
    listAList.add(temp);To compare the two lists, the easiest option would be to iterate through one ArrayList and ceheck to see if the values you recover from it are duplicated in the other ArrayList. Luckilly, ArrayList has another method that helps here, it is called contains();
    Assuming that you have two ArrayList(s), one called listAList that holds the Strings that belong to List A and another called listBList that holds the Strings that belong to ListB, you could do something like this to check for duplicates;
    for(String element : listAList) {
        if(listBList.contains(element)) {
            System.out.println("Found a match");
    }Hope that helps.

Maybe you are looking for

  • IPod rings but not iPad when Facetime call comes in

    When I Facetime my wife only her iPod rings and NOT he iPad.  However she can answer the call on either device.  Any comments are appreciated.

  • How big of a root partition should I have?

    I am new to Archlinux and Linux in general. I recently installed my first Arch system but I have not yet installed a desktop environment for I am trying to learn the command line.  I was planning on using this weekend to set up a desktop environment

  • Can I use the value returned from a Text Function in another Formula?

    I'm writing a report in Hyperion System 9 BI + Financial Reporting Studio version 9.2. I have 2 grids in my report. Grid1 Column A is set up as a text function using the function type - <<GetCell("Grid2", 1, a, 1)>>. I would like to use the values re

  • Error in Queue

    Hi Everyone I have the following problem with my XI screnario. I would like to send an IDoc from SAP to third party system. In XIu2019s Message monitor the Message is in status u201CScheduledu201D and the Queue status is u201CMessage has Errorsu201D.

  • R3 dev to XI server

    HI, After uploading data to a z table in R3 server, can we make a XI scenario to be executed in XI server automatically. Means i do not logon to xi server, through R3 server only I want to execute XI scenario. Will this be possible?? Plz share... reg