Clear arrayList

Anyone can help explain this to me. Which one is faster and why?
manager.clearAllocationList();
manager.getEditedAllocList().clear();
This method in different class: -
public void clearAllocationList() {
allocationList.clear();
Thanks in advance.

First the two examples aren't equivalent so its meaningless to try to compare them.
Second, it's not important which one is faster as the time difference will be so small you won't be able to measure it.
Don't waste your time worrying about such minor things.
If you really want to know which is more efficient, then write your own test program.

Similar Messages

  • ArrayList clears when placed in HashMap

    I have a series of ArrayLists (argValues), to be used as the values in a HashMap. They are not empty when they are placed in the table, but when I try to get one of them out, the ArrayList that is returned is empty. Here is the part of my code that has the problem. I'm parsing an XML file beforehand (doc_cmd is the Document into which the XML was parsed):
               NodeList nl_cmd = doc_cmd.getElementsByTagName("RFSW_CMD_PKT");
               if (doc_cmd != null) {
                   for(int i = 0; i < nl_cmd.getLength(); i++) {
                        if (!nl_cmd.item(i).getNodeName().equals("#text")) {
                            String key = nl_cmd.item(i).getAttributes().getNamedItem("NAME").getNodeValue();
                            //   System.out.println(key);
                            Element currentCmd = (Element) nl_cmd.item(i);
                            NodeList nlChildren = currentCmd.getChildNodes();
                            ArrayList argValues = new ArrayList();
                            for (int j = 0; j<nlChildren.getLength(); j++) {
                                if (!nlChildren.item(j).getNodeName().equals("#text")) {
                                    nodeName = nlChildren.item(j).getNodeName();
                                    if (!nodeName.equals("BITFIELD") && !nodeName.equals("UNION"))
                                        argName = nlChildren.item(j).getAttributes().getNamedItem("NAME").getNodeValue();
                                    else
                                        argName = "";
                                    value = nodeName + "_" + argName;
                                    argValues.add(value);
                            // THIS IS WHERE THE PROBLEM IS
                            System.out.println("ARGVALUES SIZE = " + argValues.size());
                            hashcmds.put(key, argValues);
                            argValues.clear();
                            ArrayList yo = (ArrayList)hashcmds.get(key);
                            System.out.println("SIZE = " + yo.size());

    Note that you're calling the clear method on the
    object you've inserted, not a copy of it. You should
    clone() itIn this case I there is no point in cloning the ArrayList because it goes out of scope. He isn't resuing it and there was never a reason to clear it anyway. The solution is to just not clear the ArrayList.
    If one were attempting to reuse it in that manner, cloning an ArrayList and clearing it to use again is less efficient than just creating a new one and letting the old one go out of scope.
    The steps required to fill clone and reuse.
    1. create new ArrayList
    2. copy references
    3. clear entries
    4. insert n refereneces
    The steps required to just create new
    1. create new ArrayList
    2. insert n references
    By clearing the ArrayList here, you are just doing more work.

  • Clear memory usage

    Hello,
    I have created a web app. I'm using Ubuntu 10.04, Netbeans 6.9 and Tomcat 6 server.
    My application is based on Apache Lucene search. (I'm not sure, maybe Lucene is causing my problem, but I doubt it.)
    My problem is:
    When I search for some data, for e.g a word which is String, I store the results in ArrayLists. But everytime I send a request to servlet, I clear arraylists by doing this:
    ArrayList.clear();But my memory usage is rising on every search. And finally, I get my system using full memory.
    Mem:
    total       used       free     shared    buffers     cached
    4025       3860        164          0         54       1267What could cause this?
    Maybe I have to clear "cached" somehow?
    Edited by: peliukasss on Aug 24, 2010 11:39 AM

    peliukasss wrote:
    My problem is:
    When I search for some data, for e.g a word which is String, I store the results in ArrayLists. But everytime I send a request to servlet, I clear arraylists by doing this:
    ArrayList.clear();
    That's most likely unnecessary, unless you're keeping references to those arraylists needlessly somewhere. You're not storing them into the session are you?
    But my memory usage is rising on every search. And finally, I get my system using full memory.
    Mem:
    total       used       free     shared    buffers     cached
    4025       3860        164          0         54       1267What could cause this?The operating system uses the memory for caching and such if it can, because free memory has no intrinsic value. It can and will get rid of some cache if memory is required.
    Maybe I have to clear "cached" somehow?No, that's what the operating system keeps cached. Java has nothing to do with that.
    The actual used memory is seen on the second line, which counts out the buffers and cache, such as on my machine:
                 total       used       free     shared    buffers     cached
    Mem:          3837       3766         71          0         51       1640
    -/+ buffers/cache:       2074       1762
    Swap:        11240        378      10862Even though it might seem I have only 71 megabytes of free memory, there's actually 1.7GB free.
    You can give less memory for tomcat if you don't want it to go that high, look into the starting options. But there's nothing bizarre about what you're seeing.

  • Error in @Override while chaning from JDK1.6 to JDk1.5

    Hi,
    I am getting following error while migrating from JDK1.6 to JDK1.5.
    Multiple markers at this line
         - implements org.quartz.Job.execute
         - The method execute(JobExecutionContext) of type TransferFiles must override a superclass
         method
    I have a class which implements Job interface having one method execute(JobExecutionContext context) . I am overriding this method inside one of my class by using @Override annotataion.
    It is working absolutely fine in JDK1.6 but while migrating to JDK1.5 it is showing the above error.
    Kindly help me in this regard.
    Thanks,
    AK

    Thank you very much for your kind help. I would like to tell you that by changing my enviroment to JDK1.5 from JDK1.6 it is asking for change the project facet. After changing the Project Facet from 6.0 to 5.0 I am getting error at @Override annotation line.
    I am sharing my code here.
    @Override
         public void execute(JobExecutionContext arg0) throws JobExecutionException {
              System.out.println("Quartz Scheduler: " + new Date());
              errFileList.clear();
              ArrayList<String> inputFileList = new ArrayList<String>();
              try {
                   Authenticate.setUser();
                   inputFileList = getInputFileList(yesterdayDate());
                   int x = 0;
                   Iterator<String> inputIterator = inputFileList.iterator();
                   while (inputIterator.hasNext()) {
                        String inputFile = inputIterator.next();
                        StringTokenizer st = new StringTokenizer(inputFile, "&");
                        String output = null;
                        while (st.hasMoreTokens()) {
                             String view = (String) st.nextElement();
                             if (view.startsWith("view")) {
                                  StringTokenizer st1 = new StringTokenizer(view, "=");
                                  while (st1.hasMoreTokens()) {
                                       output = (String) st1.nextElement();
                        x++;
                        String outputFile = OUTPUT_FILES + output + XML;
                        getAuthentication(Authenticate.getUserId(), Authenticate
                                  .getPassword());
                        status = copyfile(inputFile, outputFile, x);
                        runTime();
                   runDate();
                   LOG.info("Error Files Are : " + getErrorFileList());
                   LOG.info("No of Error Files : " + errFileList.size());
                   if ((null != status) && (errFileList.size() > 0)) {
                        setSendMail(true);
                        EmailHandler
                                  .dispatchEmail(toMailList(), Email.ERROR_FILES,
                                            TransferFiles.getErrorFileList().toString(),
                                            Email.FROM);
                   // readLogfile(
                   // "C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/XmlFileTransformation/FileTransform.log"
              } catch (Exception e) {
                   System.out.println("Exception" + e);
                   LOG.error("Exception" + e);
    Here I have two suggestions coming by eclipse.
    1.create execute method in super type ToolConstants
    2.Remove @Override annotation.
    but I have the same method inside an interface named as Job. So after removing the @Override annotation
    I am getting the following runtime exception.
    javax.servlet.ServletException: Servlet execution threw an exception
    root cause
    java.lang.NoClassDefFoundError: javax/activation/DataSource
         fileTransform.FileTransServlet.doPost(FileTransServlet.java:52)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    Please help me.
    Thanks,
    Ak

  • Data Collection Program...

    I have to code a program that will collect data from 4 textboxes and from a option box array of 5 choices. (0-5 w/ 0 being setState to true so to have no boxes checked upon startup). Then the program has to have two buttons one to clear data and one to submit the data. When the data is submitted it has to check for empty fields or not selected checkboxes. Then it will send it to a data file. The interface must be a windowed interface, not an applet so I suppose a panel would be accurate, with a dropdown menu with a submit and clear command. I have a beginning understanding of java (I'm a little slow at programming), but this is pretty far over my head. Any snippets of code or template type code would be awesome. You don't have to do it for me, but a structure without the filling would be nice. Anyways, thanks for all your help!
    Arvida

    Well I am not sure what you want to use.Do you want to use a jcheckbox or a
    JCoboBox also when you say a windows interface I take it you mean a graphical user interface(gui)?? Well anyways here is the frame work For a JComboBox .
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.ArrayList;
    public class junk extends JFrame implements ItemListener,ActionListener {
      JButton button1 = new JButton("submit"); 
      JButton button2 = new JButton("clear");
      ArrayList getit = new ArrayList();
      JComboBox box = new JComboBox(//String array);
      JTextField lab = new JTextField(20);
      String answer;
      int stat;
      public junk() {
        super();
        setSize(int,int);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container pane = getContentPane();
        pane.setLayout(//need a layoutmanger);
        box.// need to add a listener;
        lab.setText(data[0]);
        pane.add(box);
        pane.add(lab);
        button1.//need to add a listener;
        button2.//need to add a listener;
        pane.add(button1);
        pane.add(button2);
        setVisible(true); 
    public void itemStateChanged(ItemEvent ieve) {//work needs to be done}
    public void actionPerformed(ActionEvent eve) {/work needs to be done}
      public static void main(String[] args) {
        junk test = new junk();
    } well here is a skeleton of what I have come up with all ya have to do is put it together.

  • HELP creating random rectangle

    hi im having trouble it seems like my code is down correct but that isnt the case because i get 4 errors all involving 'MyRectangle' i get 4 cannot find symbol if ne one knows please help me out thanks my code is below thank you
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Random;
    import javax.swing.*;
    public class DrawJPanel extends JPanel
       // Random object to create random numbers
       private Random randomNumber = new Random();
       // Timer object to generate events
       private Timer drawTimer;
       // ArrayList object to hold MyRectangle objects
       private ArrayList rectangleArrayList = new ArrayList();
       // array of possible MyRectangle colors
       private Color[] colors = { Color.BLUE, Color.ORANGE, Color.PINK,
          Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK,
          Color.WHITE, Color.RED, Color.GREEN };
       // no-argument constructor
       public DrawJPanel()
          super();
          drawTimer = new Timer( 250,
             new ActionListener() // anonymous inner class
                // event handler called every 250 microseconds
                public void actionPerformed( ActionEvent event )
                   drawTimerActionPerformed();  
             } // end anonymous inner class
          ); // end call to new Timer
          drawTimer.start(); // start timer
       }  // end contructor
       // create new MyRectangle object and add it to rectangleArrayList
       private void drawTimerActionPerformed()
          // get random dimensions and a random color
          int x = randomNumber.nextInt( 380 );
          int y = randomNumber.nextInt( 380 );
          int width = randomNumber.nextInt( 150 );
          int height = randomNumber.nextInt( 150 );
          int color = randomNumber.nextInt( 10 );
          // create MyRectangle object and add it to rectangleArrayList
          MyRectangle rectangle = new MyRectangle(x,y,width,height,colors[color]);
          rectangleArrayList.add( rectangle );
          repaint();
       } // end method drawTimerActionPerformed
       // draw all rectangles
       public void paintComponent( Graphics g )
          super.paintComponent( g );
          // create iterator
          Iterator rectangleIterator = rectangleArrayList.iterator();
          MyRectangle currentRectangle; // create MyRectangle
          // iterate through ArrayList and draw all MyRectangles
          while ( rectangleIterator.hasNext() )
             currentRectangle =
                ( MyRectangle ) rectangleIterator.next();
             currentRectangle.draw( g ); // draw rectangle
       } // end method paintComponent
       // clear rectangleArray
       public void clear()
          rectangleArrayList.clear(); // clear ArrayList
          repaint(); // repaint JPanel
       } // end method clear
    } // end class DrawJPanel

    And...?
    MyRectangle is not part of the Java API. So that means you wrote it... or something like that. Did you write a MyRectangle class?

  • List.clear() outside of List finalList = new ArrayList(); will delete element in finalList?

    Hello all!
    I am using 3 ArrayLists.
    the first is List<String>
    the second is List<String[]>
    and the third is a list of those lists List<List>
    I use the first list to get the string I need, but I use the second for String.split.
    I then need to keep a list of these to use, so I need the third List.
    After adding the second list to the list of lists I want to clear it so I can set up the next list to be added, but if I do list.clear(); it will delete everything in that list.
    If I do not clear it, it is fine.
    At first I wasn't sure if it was my fault, because I'm not sure if I ever had to do that before, so I made a test case that yields the result if I change the element outside.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    * @author Konrad
    public class JavaApplication1 {
         * @param args the command line arguments
        String a;
        List<String> j = new ArrayList<>();
        public JavaApplication1()
            a();
        public void a()
            a = "ADASDSADSA";
            j.add(a);
            a = null;
            System.out.println(j);
        public static void main(String[] args) throws SQLException {
            JavaApplication1 a = new JavaApplication1();
    If I change a = null to a = ""; it still yields the original a = "ADASD......";
        protected List<String> list = new ArrayList<>();
        protected List<String[]> list2 = new ArrayList<>();
        protected List<List> finalList = new ArrayList<>();
      finalList.add(list2);
                     //list2.clear();
    With this I yield an empty array element, even though my array elements exist.  I tried using multiple lists and I just had multiple empty elements.
    So again I'm not sure if I did something wrong, or is this a bug?  Since my test case worked, I'm confused.
    Thanks!
    ~KZ

    After adding the second list to the list of lists I want to clear it so I can set up the next list to be added, but if I do list.clear(); it will delete everything in that list.
    Correct - you are just working with multiple references to the SAME set of objects.
    Use 'remove' to remove an element from a list and then 'add' to add it to the other list.
    See the Javadocs for the 'remove' method of the List interface
    http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(int)
    remove
    E remove(int index)
    Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.   
    Parameters: 
    index - the index of the element to be removed 
    Returns: 
    the element previously at the specified position 
    Throws: 
    UnsupportedOperationException - if the remove operation is not supported by this list 
    IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

  • Clear() vs. removeAll() for an ArrayList

    What's the difference between clear() and removeAll() for an ArrayList?
    Does one actually garbage collect the memory? Is one better for synchronized situations?
    From the documentation it's not clear how they differ except that removeAll uses an iterator and clear() doesn't give details.
    Anyone have a link to more info?
    Thanks!

    I do not find a removeAll() method in ArrayList!
    I find a method removeAll(Collection c)
    it takes a Collection as a parameter.
    here is it's specification
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html#removeAll(java.util.Collection)
    when you call this method on an ArrayList, it takes the Collection passed as a parameter and if an element in the passed collection exists in the ArrayList then the element is removed.
    The clear() method is specified here
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html#clear()
    I think it's purpose is "clear" (pun intended)
    sincerely
    Walken16

  • Iterator remove versus ArrayList clear

    Hi,
    I iterate through an ArrayList, and the last thing I do is call (Iterator)it.remove(). I am wondering if the performance is better, worse, or equal to if I was to not call it.remove() but instead just clear() the ArrayList after exiting the loop.
    Can someone tell me the tradeoffs, or if they are equal? I am interested in performace.
    Thanks.

    Since you'd have to call remove once for every element in the list, I would think that clear would be faster.
    However...
    * Put it on a profiler or mark start/end time on a lage list to get a concrete mesaurement, rather than guessing.
    * If possible, just getting rid of the list and creating a brand new one when you need it will probably be better than either of the other methods.
    * This is a microoptimization that should only be done after a profiler tells you that this is a bottleneck. Until then, use whichever idiom more closely matches your intent.

  • ArrayList - clear() or new ArrayList() ?

    Hi everybody,
    I have a loop which runs ~100-100000 times and in each looping an ArrayList is filled and holds elements ranging from 1 to 30000. I'm reusing the list and I'm wondering whether I should use clear() or better reinstantiate the List.
    I know that with StringBuffer the setLength(0) does not decrease the capacity of the StringBuffer, so that it might take much more memory than it actually needs.
    How about List?
    Does clear() decrease the capacity of the List?
    Would a reinstantiation be the better way?
    Or doesn't it matter anyway and a list with too much capacity is fine to use?
    Hope you can help
    Cheers
    bgcl

    Hi everybody,
    I have a loop which runs ~100-100000 times and in each
    looping an ArrayList is filled and holds elements
    ranging from 1 to 30000. I'm reusing the list and I'm
    wondering whether I should use clear() or better
    reinstantiate the List.
    I know that with StringBuffer the setLength(0) does
    not decrease the capacity of the StringBuffer, so that
    it might take much more memory than it actually
    needs.
    How about List?
    Does clear() decrease the capacity of the List?
    Would a reinstantiation be the better way?
    Or doesn't it matter anyway and a list with too much
    capacity is fine to use?
    Hope you can help
    Cheers
    bgclclear() will be better than new ArrayList() but the performance difference of clear() and new ArrayList(int) (with an int of an appropriate size) will be negligable.

  • ArrayList help

    ok still having trouble, i redid alot of the program, i need to slim down the ArrayList to being one instance of a word per file, plus all of the lines they are on inside that one instance. Right now there are mulitple instances of each word and each one has its own line its on. I have tried for the past 3 hours trying to get this to work, anything from finding a way to sort it then compair first and last index's to moving them to arrays and manually doing it. I just cant figure this out any help would be great!
    just for refrance the arguement taken is a text file that lists other text files which have plain text in them
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    class FileParser
         static ArrayList files = new ArrayList();
         JFrame frame = new JFrame("Search Engine v1.0");
         JTextField text = new JTextField(20);
         JTextArea display = new JTextArea(20,20);
         int xPosition;
         int yPosition;
         static int testCounter = 0;
         FileObj fo;
         //ArrayList <Word>finalWord = new ArrayList<Word>();
         public static void main(String[] args)
              FileParser fp = new FileParser(args[0]);
              fp.GUI(); disabling GUI for now
         public FileParser(String s)
              String option = "";
              try
                   BufferedReader br = new BufferedReader(new FileReader(s));
                   String inLine = br.readLine();
                   while(inLine != null)
                        FileObj fo = new FileObj(inLine);
                        fo.processFile();
                        files.add(fo);
                        inLine = br.readLine();
                        System.out.println("test");
                   br.close();//the arraylist files now has each file name that containes words
                   System.out.println(files);
              catch(IOException e){}
         public void GUI()
              Container con;
              JLabel l1;
              JPanel top, middle, bottom;
              con = frame.getContentPane();
              con.setLayout(new BorderLayout());
              top = new JPanel(new GridLayout(1,3));
              middle = new JPanel(new GridLayout(2,1));
              bottom = new JPanel(new GridLayout(1,3));
              top.add(new JLabel("Search for:"));
              top.add(text);
              middle.add(new JLabel("Results: "));
              middle.add(new JScrollPane(display));
              JButton search = new JButton("Search");
              search.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   //System.out.println(text.getText());
                   FileObj.list(text.getText());
              JButton clear = new JButton("Clear");
              clear.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   text.setText("");
                   display.setText("");
              JButton exit = new JButton("Exit");
              exit.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   System.exit(0);
              bottom.add(search);
              bottom.add(clear);
              bottom.add(exit);
              con.add(top, BorderLayout.NORTH);
              con.add(middle, BorderLayout.CENTER);
              con.add(bottom, BorderLayout.SOUTH);
              frame.setSize(400, 250);
              frame.setVisible(true);
    import java.util.*;
    import java.io.*;
    class FileObj
         String fileName;
         int wordCount;
         int uniqueWords;
         int lineCount;
         ArrayList <Word>words = new ArrayList<Word>();
         Boolean first = true;
         FileObj(String theFiles)
              fileName = theFiles;//individual file name
              System.out.println(fileName);
         public void processFile()
              FileReader infile = null;//helps load files text for reading
              StreamTokenizer reader = null;//helps tokenizes the files text
              int testCounter = 0;
              try
                   infile = new FileReader(fileName);//finishes loading files text
                   reader = new StreamTokenizer(infile);//finishes tokenizing files text
                   reader.wordChars(65, 122);//tells it to only take letters
                   reader.nextToken();
                   while (reader.ttype != reader.TT_EOF)// while the end of the stream hasnt been reached
                        if (reader.ttype == reader.TT_WORD)//if the stream has read a token
                             String token = reader.sval;//creates a string with the token in it
                             wordCount++;
                             token = stripWord(token);//strips token of non letters
                             processWord(token, reader.lineno(), fileName);
                        reader.nextToken();
                        lineCount = reader.lineno();// gets me the line number
                   exists();
                   testCounter = words.size();
                   for(int i = 0; i<testCounter;i++)
                        System.out.println(words.get(i));
                   infile.close();
                   //try to print out a search
              catch(FileNotFoundException e){}
              catch(IOException e){}
         public String toString()
              return ("FileName: "+fileName+" WordCount: "+wordCount+" UniqueWords:"+uniqueWords+" LineCount: "+lineCount);
         public String stripWord(String w)
              w = w.replace('.',' ');
         w = w.replace(',',' ');
         w = w.replace('?',' ');
         w = w.replace(':',' ');
         return w.trim().toUpperCase();
         public void processWord(String s, int line, String f)
              Word wordObj = new Word(s, line, f);
              words.add(wordObj);
              (words);
            public void exists()// this is only to find if the word exists
              int arrayCounter= 0;
              //words
         }     public static String list(String w)
              System.out.println("do i see this?");
              return w;
    /* Word wordObj = finalWord.get(w.toUpperCase());
    if (wordObj != null)
    System.out.println(w + " found in " + fileName + " at lines " + wordObj.lineNumbers.toString());
    import java.util.*;
    class Word
         String value;
         String fileName;
         int count;
         ArrayList lineNumbers;
         public Word(Word wordCopy)
              value = wordCopy.value;
              fileName = wordCopy.fileName;
              count = wordCopy.count;
              lineNumbers = wordCopy.lineNumbers;
         public Word(String v, int l, String f)
              value =v;
              fileName = f;
              lineNumbers = new ArrayList();
              lineNumbers.add(new Integer(l));
              count++;
              //System.out.println("god i hope i see the unique words, this is one: "+value+" "+lineNumbers);
         public Word(String v)
              value = v;
         public void update(int l)
              lineNumbers.add(new Integer(l));
              count++;
         public String toString()
              return "FileName:"+fileName+" Word:"+value+" Lines found in: "+lineNumbers;
         public String getWord()
              return value;
         public int getEverything()
              int size = count;
              return size;
         public boolean compairTo(String s1)
              if(value.equals(s1))
                   return true;
              else
                   return false;
    }

    ok i put it all inside code brackets, i was told you only the part i was having trouble with. But i explained what the program does and im just trying to get the ArrayList which is filled with my Word objects to become sorted kind of. Right now it will have multiple instances of exact words, but they will be on diffrent lines, i need to shorten it down and put the lineNumbers all into the same word object if they are the same String value.import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    class FileParser
    static ArrayList files = new ArrayList();
    JFrame frame = new JFrame("Search Engine v1.0");
    JTextField text = new JTextField(20);
    JTextArea display = new JTextArea(20,20);
    int xPosition;
    int yPosition;
    static int testCounter = 0;
    FileObj fo;
    //ArrayList <Word>finalWord = new ArrayList<Word>();
    public static void main(String[] args)
    FileParser fp = new FileParser(args[0]);
    fp.GUI(); disabling GUI for now
    public FileParser(String s)
    String option = "";
    try
    BufferedReader br = new BufferedReader(new FileReader(s));
    String inLine = br.readLine();
    while(inLine != null)
    FileObj fo = new FileObj(inLine);
    fo.processFile();
    files.add(fo);
    inLine = br.readLine();
    System.out.println("test");
    br.close();//the arraylist files now has each file name that containes words
    System.out.println(files);
    catch(IOException e){}
    public void GUI()
    Container con;
    JLabel l1;
    JPanel top, middle, bottom;
    con = frame.getContentPane();
    con.setLayout(new BorderLayout());
    top = new JPanel(new GridLayout(1,3));
    middle = new JPanel(new GridLayout(2,1));
    bottom = new JPanel(new GridLayout(1,3));
    top.add(new JLabel("Search for:"));
    top.add(text);
    middle.add(new JLabel("Results: "));
    middle.add(new JScrollPane(display));
    JButton search = new JButton("Search");
    search.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    //System.out.println(text.getText());
    FileObj.list(text.getText());
    JButton clear = new JButton("Clear");
    clear.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    text.setText("");
    display.setText("");
    JButton exit = new JButton("Exit");
    exit.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    bottom.add(search);
    bottom.add(clear);
    bottom.add(exit);
    con.add(top, BorderLayout.NORTH);
    con.add(middle, BorderLayout.CENTER);
    con.add(bottom, BorderLayout.SOUTH);
    frame.setSize(400, 250);
    frame.setVisible(true);
    import java.util.*;
    import java.io.*;
    class FileObj
    String fileName;
    int wordCount;
    int uniqueWords;
    int lineCount;
    ArrayList <Word>words = new ArrayList<Word>();
    Boolean first = true;
    FileObj(String theFiles)
    fileName = theFiles;//individual file name
    System.out.println(fileName);
    public void processFile()
    FileReader infile = null;//helps load files text for reading
    StreamTokenizer reader = null;//helps tokenizes the files text
    int testCounter = 0;
    try
    infile = new FileReader(fileName);//finishes loading files text
    reader = new StreamTokenizer(infile);//finishes tokenizing files text
    reader.wordChars(65, 122);//tells it to only take letters
    reader.nextToken();
    while (reader.ttype != reader.TT_EOF)// while the end of the stream hasnt been reached
    if (reader.ttype == reader.TT_WORD)//if the stream has read a token
    String token = reader.sval;//creates a string with the token in it
    wordCount++;
    token = stripWord(token);//strips token of non letters
    processWord(token, reader.lineno(), fileName);
    reader.nextToken();
    lineCount = reader.lineno();// gets me the line number
    exists();
    testCounter = words.size();
    for(int i = 0; i<testCounter;i++)
    System.out.println(words.get(i));
    infile.close();
    //try to print out a search
    catch(FileNotFoundException e){}
    catch(IOException e){}
    public String toString()
    return ("FileName: "+fileName+" WordCount: "+wordCount+" UniqueWords:"+uniqueWords+" LineCount: "+lineCount);
    public String stripWord(String w)
    w = w.replace('.',' ');
    w = w.replace(',',' ');
    w = w.replace('?',' ');
    w = w.replace(':',' ');
    return w.trim().toUpperCase();
    public void processWord(String s, int line, String f)
    Word wordObj = new Word(s, line, f);
    words.add(wordObj);
    (words);
         public void exists()// this is only to find if the word exists
              int arrayCounter= 0;
              //words
    public static String list(String w)
    System.out.println("do i see this?");
    return w;
    /* Word wordObj = finalWord.get(w.toUpperCase());
    if (wordObj != null)
    System.out.println(w + " found in " + fileName + " at lines " + wordObj.lineNumbers.toString());
    import java.util.*;
    class Word
    String value;
    String fileName;
    int count;
    ArrayList lineNumbers;
    public Word(Word wordCopy)
    value = wordCopy.value;
    fileName = wordCopy.fileName;
    count = wordCopy.count;
    lineNumbers = wordCopy.lineNumbers;
    public Word(String v, int l, String f)
    value =v;
    fileName = f;
    lineNumbers = new ArrayList();
    lineNumbers.add(new Integer(l));
    count++;
    //System.out.println("god i hope i see the unique words, this is one: "+value+" "+lineNumbers);
    public Word(String v)
    value = v;
    public void update(int l)
    lineNumbers.add(new Integer(l));
    count++;
    public String toString()
    return "FileName:"+fileName+" Word:"+value+" Lines found in: "+lineNumbers;
    public String getWord()
    return value;
    public int getEverything()
    int size = count;
    return size;
    public boolean compairTo(String s1)
    if(value.equals(s1))
    return true;
    else
    return false;

  • Arraylist issue: pass all the arrayList `s object to other arrayList ...

    hi all...i hope somebody could show me some direction on my problem...i want to pass a arraylist `s cd information to an other arraylist
    and save the new arraylist `s object to a file...i try to solve for a long ..pls help...
    import java.text.*;
    import java.util.*;
    import java.io.*;
    public class Demo{
         readOperation theRo = new readOperation();
         errorCheckingOperation theEco = new errorCheckingOperation();
         ArrayList<MusicCd>  MusicCdList;
         private void heading()
              System.out.println("\tTesting read data from console, save to file, reopen that file\t");
         private void readDataFromConsole()
         //private void insertCd()
            MusicCdList = new ArrayList<MusicCd>( ); 
            MusicCd theCd;
            int muiseCdsYearOfRelease;
            int validMuiseCdsYearOfRelease;
            String muiseCdsTitle;
              while(true)
                    String continueInsertCd = "Y";
                   do
                        muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
                        muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
                        validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);
                        MusicCdList.add(new MusicCd(muiseCdsTitle, validMuiseCdsYearOfRelease));//i try add the cd`s information to the arrayList
                        MusicCdList.trimToSize();
                        //saveToFile(MusicCdList);
                        continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
                   }while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
                   if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
                                                    //MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));                              
                        break;
                      //System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
         //i want to pass those information that i just add to the arrayList to file
         //I am going to pass the arraylist that contains my cd`s information to new arraylist "saveitems and save it to a file...
         //i stuck on this problem
         //how do i pass all the arrayList `s object to another arraylist ..pls help
         //it is better show me some example how to solve thx a lot
         private void saveToFile(ArrayList<MusicCd> tempItems)
              ArrayList<MusicCd> saveItems;
              saveItems = new ArrayList<MusicCd>();
              try
                   File f = new File("cdData.txt");
                   FileOutputStream fos = new FileOutputStream(f);
                   ObjectOutputStream oos = new ObjectOutputStream(fos);
                   saveItems.add(ArrayList<MusicCd> tempItems);
                   //items.add("Second item.");
                   //items.add("Third item.");
                   //items.add("Blah Blah.");
                   oos.writeObject(items);
                   oos.close();
              catch (IOException ioe)
                   ioe.printStackTrace();
              try
                   File g = new File("test.fil");
                   FileInputStream fis = new FileInputStream(g);
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   ArrayList<String> stuff = (ArrayList<String>)ois.readObject();
                   for( String s : stuff ) System.out.println(s);
                   ois.close();
              catch (Exception ioe)
                   ioe.printStackTrace();
         public static void main(String[] args)
              Demo one = new Demo();
              one.readDataFromConsole();
              //one.saveToFile();
              //the followring code for better understang
    import java.io.Serializable;
    public class MusicCd implements Serializable
         private String musicCdsTitle;
            private int yearOfRelease;
         public MusicCd()
              musicCdsTitle = "";
              yearOfRelease = 1000;
         public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
              musicCdsTitle = newMusicCdsTitle;
              yearOfRelease = newYearOfRelease;
         public String getTitle()
              return musicCdsTitle;
         public int getYearOfRelease()
              return yearOfRelease;
         public void setTitle(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
         public void setYearOfRelease(int newYearOfRelease)
              yearOfRelease = newYearOfRelease;
         public boolean equalsName(MusicCd otherCd)
              if(otherCd == null)
                   return false;
              else
                   return (musicCdsTitle.equals(otherCd.musicCdsTitle));
         public String toString()
              return("Music Cd`s Title: " + musicCdsTitle + "\t"
                     + "Year of release: " + yearOfRelease + "\t");
         public ArrayList<MusicCd> getMusicCd(ArrayList<MusicCd> tempList)
              return new ArrayList<MusicCd>(ArrayList<MusicCd> tempList);
    import java.util.Scanner;
    import java.util.InputMismatchException;
    import java.util.NoSuchElementException;
    public class errorCheckingOperation
         public int errorCheckingInteger(int checkThing, int lowerBound, int upperBound)
               int aInt = checkThing;
               try
                    while((checkThing < lowerBound ) || (checkThing > upperBound) )
                         throw new Exception("Invaild value....Please enter the value between  " +  lowerBound + " & " +  upperBound );
               catch (Exception e)
                 String message = e.getMessage();
                 System.out.println(message);
               return aInt;
           public int errorCheckingSelectionValue(String userInstruction)
                int validSelectionValue = 0;
                try
                     int selectionValue;
                     Scanner scan = new Scanner(System.in);
                     System.out.print(userInstruction);
                     selectionValue = scan.nextInt();
                     validSelectionValue = errorCheckingInteger(selectionValue , 1, 5);
               catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return validSelectionValue;
    import java.util.*;
    public class readOperation{
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    }

    sorry for my not-clear descprtion...thc for your help....i got a problem on store some data to a file ....u can see my from demo..
    Step1: i try to prompt the user to enter his/her cd `s information
    and i pass those cd `s information to an object "MuiscCd" ..and i am going to add this "MuiscCd" to the arrayList " MusicCdList ". i am fine here..
    Step2: and i want to save the object that `s in my arrayList " MusicCdList " to a file....i got stuck here..<_> ..(confused).
    Step3:
    i will reopen the file and print it out..(here i am alright )

  • Arraylist Improperly transfered through ObjectStreams

    code from client:
    public void listen()
           String readtext;
           field.setText("");
           System.out.println("Starting to Listen");
           while(!socket.isClosed()){
                     try{
                    dataType obj = (dataType)(in.readObject());
                    switch(obj)
                         case String:
                         readtext = in.readUTF();
                         field.append(readtext);
                         System.out.println("Text recieved: " + readtext);
                         break;
                         case Userlist:
                         System.out.println("USERLIST UPDATE");
                         setUserList((Userlist)(in.readObject()));
                         break;
                            } catch (IOException e){}
                            catch(ClassNotFoundException cnfe){cnfe.printStackTrace();}
      private void setUserList(Userlist ul)
           System.out.println((ul.size()) + " Users");
           userlist.removeAll();
           for(int i = 0; i < ul.size(); i++)
           userlist.add(((User)(ul.get(i))).getName());
      }code from server's client threads:ClientWorker(Socket client, Server s) {
       this.client = client;
       this.server = s;
    public void run(){
        String line;
        try{
          in = new ObjectInputStream(client.getInputStream());
          out = new ObjectOutputStream(client.getOutputStream());
        } catch (IOException e) {
          System.out.println("in or out failed");
          System.exit(-1);
        try{
         String userName = in.readUTF();
         This = new User(userName);
         server.UserNames.add(This);
         server.updateList();
         userset = true;
         } catch(IOException ieo){}
      ...code from server:  public void updateList()
           System.out.println((UserNames.size()) + " Users");
           for(int i = 0; i < Users.size(); i++)
           try{((ClientWorker)Users.get(i)).getOutputStream().writeObject(dataType.Userlist);
                ((ClientWorker)Users.get(i)).getOutputStream().writeObject(UserNames);
                catch(IOException e){e.printStackTrace();}
      }this code improperly prints the userlist (extends Arraylist) usernames object from the server to the clients
    for one client, userlist usernames.size() = 1, works for both server and client...
    for two clients:
    client one:
    userlist usernames.size() = 1 <- incorrect
    client two:
    userlist usernames.size() = 2 <- correct
    it seems that after the first time the server sends the client the list that the list doesnt change on the client even though it is sending the same userlist object to all the clients

    Your posted code is too fragmented to get clear understanding but if you are sending a same object repeatedly, try using writeUnshared() method instead of writeObject().

  • HOW DO I KEEP AN ARRAYLIST IN RANDOM ORDER AFTER EXITING THE SUB ROUTINE CONTAINING IT

    PLEASE HELP!I am trying to go from VB4 which I loved to VB2010 which I find somewhat more challenging. I’ve searched the web for help and have adapted the following to my project. This code does
    rotate randomly through every card in the deck and displays unique cards until all have been drawn. BUT I want to draw one card
    only from the first “hat” of Boy’s names; then draw the second card from the second “hat” of Girl’s names and repeat this process until all cards in both decks have been drawn. How do I get the TextBox (OR any
    MsgBox) to display JUST ONE unique random card at a time so I can exit that deck and go to the next deck?
    On my form, I have two TextBoxes (to display the names (as drawn), two buttons (to re-load each deck once exhausted) and one command (&End)control (to end the process). I created two ArraysLists
    (to hold the Boys names and Girls names separately) and two ArrayLists to hold the cards for the random decks when created in code.
    I can
    NOT get this code to draw random UNIQUE names once I exit the deck. I have tried to ReDim the deck; randomly pull a card from the second (temp) deck, etc
    NOTHING seems to work.
    WHY does my deck lose randomness once I exit it?
    How can I fix it? I don’t understand this. Below is the code for the "hat" with the 10 girl's names.
    Also, when I don't loop through all the cards, I usually get "An Out of Index exception was not handled" error. Hope someone can help me with this problem. It seems like this should
    be easy BUT I'm baffled. Thank you for any help.
    Imports System.Collections.Generic
    Public Class Form1
    Dim Count As Integer
    Dim Rcard As New ArrayList
    Dim Dcard As New ArrayList
    Dim NewRDeck As New ArrayList
    Dim NewDDeck As New ArrayList
    Dim temp_Rnum As Integer
    Dim temp_Dnum As Integer
    Dim MyRand As New Random()
    Public Sub Rcards_Click(sender As Object, e As System.EventArgs) Handles Rcards.Click
    While Rcard.Count > 0
    Dim temp_Rnum As Integer = Int(MyRand.Next(Rcard.Count))
    NewRDeck(temp_Rnum) = Rcard(temp_Rnum)
    Rem Check that the ArrayLists work correctly and display properly
    MsgBox(Rcard(temp_Rnum), , "New random card selected is: ")
    Console.WriteLine(Rcard(temp_Rnum))
    Rcard.Text = (Rcard(temp_Rnum))
    REM Now remove the Rcard with the random number generated so it can't be drawn again
    Rcard.RemoveAt(temp_Rnum)
    End While
    REM When all 10 cards have been picked, alert player to re-load deck if desired.
    MsgBox("No new cards left in deck; please Re-Load the cards. Thank you.")
    EndSub
    End Class

    Hi Acamar,
    Thank you for such a fast response. Sorry if my text wasn't clear. I'm really struggling with creating unique random elements in Collections in VB2010 and feel I understand ArrayLists better than some of the other Collection types.The code works perfectly
    and generates unique random cards until the original deck is exhausted. Then it prompts the user to re-load the original deck so it can be reused if needed. But I need to draw one card only and exit the deck. Then when I click on the TextBox again, I want
    that deck to be in the same random order - just minus any cards I have already drawn and thrown away.  Thanks again for your help.
    Here's the rest of the code for just the girl's "hats" of names, if it helps:
    Private Sub btnShuffleRCards_Click(sender
    As System.Object, e
    As System.EventArgs)
    Handles btnShuffleRCards.Click
    Dim j As
    Integer
    For j = 1 To 10
    NewRDeck.Add(j)
    Next j
    Randomize()
    REM Create original Deck with names for the girls.
    Rcard.Add("1 HELEN”)
    Rcard.Add("2 OLIVIA")
    Rcard.Add("3 <st1:city w:st="on"><st1:place w:st="on">ALICE</st1:place></st1:city>")
    Rcard.Add("4 VALERIE")
    Rcard.Add("5 DONNA")
    Rcard.Add("6 ZELDA")
    Rcard.Add("7 MARGARIE")
    Rcard.Add("8 <st1:city w:st="on"><st1:place w:st="on">NANCY</st1:place></st1:city>")
    Rcard.Add("9 WANDA")
    Rcard.Add("10 IRENE")
    End Sub

  • Help counting a specific letter in a arrayList

    Hello I have made some code that suppose to count how many times a and e occurs in my arraylist. The problem is that it only works if an element consist of one letter. Could anyone tell me how I can make it work?
    import java.util.*;
    public class ex1
        public static void main(String[] args)
            ArrayList<String> words = new ArrayList<String>();
            words.add("ape");
            words.add("egg");
            words.add("and");
            words.add("e");
            words.add("bald");
            words.add("crap");
            averageVowels(words);
         public static void averageVowels(ArrayList<String> list)
             int count = 0;
                    for (int i = 0; i < list.size(); i++)  //for (String w: list)
                    if (list.get(i).equals("a")|| list.get(i).equals("e"))     
                           count++;
                    System.out.println(count);
    }

    baudits wrote:
    Hello I have made some code that suppose to count how many times a and e occurs in my arraylist. The problem is that it only works if an element consist of one letter. Could anyone tell me how I can make it work? How many times does it "occur" here:
    words.add("a");
    words.add("aa");Two, or three?
    If two, use String.contains("a") instead of .equals(). You're currently comparing each entire entry of your list of Strings to "a" or "e", so clearly only exactly "a" or "e" would increment count.
    If three, you'll need to iterate through each character of each word, not just through each word:
    for ( String word : words ) {
       for ( char c : word.toCharArray() ) {
          if ( c == 'a' ) {
             count++;
          } //etc
    }Edited by: endasil on 26-Nov-2009 2:55 PM

Maybe you are looking for