Arraylist.add() problem

Hi,
I'm trying to read a CSV text file into an arraylist.
I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
It just doesn't work .. I don't know why.
The arraylist I am trying to read into is
ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
but suffice to say, yes, it is kaput.
   * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
  private void custFileToArray ()
    RectangleTUI results = new RectangleTUI(); // create results object
    try   
      BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
      System.out.println("Contents of file: " + CUSTFILE); // print heading
      String line = inputStream.readLine(); // read first line
      while (line !=null) // test for end of file (EOF)
        results.loadCustFile(line);       
        line = inputStream.readLine(); // read next line
      // close file
      inputStream.close();
    // catch any file open errors
    catch(FileNotFoundException e)
      System.out.println("Error opening file: " + CUSTFILE);
      System.exit(0);
    catch(NoSuchElementException e)
      System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
    // catch any file reading errors
    catch(IOException e)
      System.out.println("Error reading from file: " + CUSTFILE);
      System.exit(0);
    System.out.println("File Reading Complete");  
  private void loadCustFile(String textLine)
    String delimiters = ","; // set tokenizer delimiter
    StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
    int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
    System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
    String cName = RecordFields.nextToken();   // Name
    String cAdd = RecordFields.nextToken();   // Street Address
    String cBurb = RecordFields.nextToken();   // Suburb
    String cPhone = RecordFields.nextToken();   // Phone
    String cEmail = RecordFields.nextToken();   // Email
    customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
  }

Cowzor wrote:
Hi,
Cheers for the replies & the printStackTrace tip.
The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
Sorry if I've mis-understood what you were saying
Here's the dummy data I'm using just incase it's at all relevant
200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
u split contains of CSV file on basis of , (comma) and read it

Similar Messages

  • ArrayLists & Database Problems

    I've created a program using Swing. My program starts up and loads data from my access database into ArrayLists. I then work on these ArrayLists in my program, adding and removing data. When i've finished, i have a save button which deletes all the data from a table in the database, then inserts the data stored in the ArrayList into the empty table. It does this sucessfully, i check the table in the database before and after.
    My problem is when i use the program again, and it loads the newly inserted data from the database into the arraylists and the JLists loads fine, but when i attempt to remove or add data from the arraylist or even query it, i get the error message:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    Any idea's why?

    i found the problem, was in the database. should get it fixed soon hopefully. Thanks anyway!

  • Reg Add problem. Convert from .reg to reg add script

    Hi. I'm making a registry script so I can add elements to the registry.
    The script is working for DWORDS but I cant get the last one to work.
    The registry exportet code I wan't to make a Reg ADD line from is:
    [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData]
    "UserFilter"=hex:41,1f,00,00,53,08,ad,ba,01,00,00,00,2c,00,00,00,01,00,00,00,\
    01,00,00,00,0c,00,00,00,9c,26,40,27,0c,f5,cf,01,01,00,00,00,07,00,6e,00,69,\
    00,74,00,6f,00,2e,00,6e,00,6f,00
    I've tried to google and have tried several reg ADD lines, but should't it be something like this?
    reg ADD "hku\temp\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData" /v UserFilter /t REG_BINARY /d
    41,1f,00,00,53,08,ad,ba,01,00,00,00,2c,00,00,00,01,00,00,00,\
    01,00,00,00,0c,00,00,00,9c,26,40,27,0c,f5,cf,01,01,00,00,00,07,00,6e,00,69,\ 00,74,00,6f,00,2e,00,6e,00,6f,00 /f
    Its the "\" that's get messy, don't know how to write reg Add line with that.
    If I skip that line the script works, I can then run the .reg file above to complete the reg. settings, but that won't solve my problem.

    Those backslashes just indicate line continuations in the .reg file.  You don't need them in your reg add version; the binary data can be placed all on one line.
    If I remember correctly, you don't need the commas when using "reg add" either, so just this should work.  I've used environment variables here to split it up across multiple lines and make it more readable, but that's not actually required:
    set REGKEY="hku\temp\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData"
    set REGDATA=411f00005308adba010000002c00000001000000010000000c0000009c2640270cf5cf010100000007006e00690074006f002e006e006f00
    reg add %REGKEY% /v UserFilter /t REG_BINARY /d %REGDATA%

  • PLZ help: ArrayList execution problem,No errors..

    but in tomcat i am getting cannot load the driver
    I dont know where i am going wrong : Just i am getting the blank page
    i am posting my code :
    --------------------LoginServlet4.java
      package com.xyz;
      import java.io.*;
      import java.util.*;
      import javax.servlet.*;
      import javax.servlet.http.*;
      import java.sql.*;
      public class LoginServlet4 extends HttpServlet
           public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
              try{
           User4 user=new User4();
           UserServices4 userServices4= new UserServices4();
           ArrayList userList = (ArrayList)userServices4.listUser4();
           req.setAttribute("userList",userList);
          RequestDispatcher rd = req.getRequestDispatcher("form5.jsp");
           rd.forward(req,res);
                }//try
                catch(Exception e)
                   System.out.println(e);
                }//catch
             }//doGet
    }---------------------UserServices4.java
    a bussiness logic class where i am opening the connection and retrieving the data
    package com.xyz;
    import java.io.*;
    import java.io.Serializable;
    import java.util.*;
    import java.sql.*;
    public class UserServices4
          public UserServices4(){}
          Connection con=null;
          PreparedStatement ps=null;
          ResultSet rs=null;
          public List listUser4(){
         ArrayList userList = new ArrayList();
         User4 user=null;
         String s1,s2,s3,s4;
          try
               Class.forName("com.jdbc.mysql.Driver");
                con=DriverManager.getConnection("jdbc:mysql://165.138.99.765/Bidding","mysql","mmmmm");
                ps=con.prepareStatement("select * from Match_Set");
                rs=ps.executeQuery();
                while(rs.next())
                   s1=rs.getString(1);
                   s2=rs.getString(2);
                   s3=rs.getString(3);
                   s4=rs.getString(4);
                   user = new User4();
                   user.setT1(s1);
                   user.setT2(s2);
                   user.setO1(s3);
                   user.setO1(s4);
                   userList.add(user);
          }//try
          catch(Exception e)
               System.out.println(e);
          finally{
               try{
                    con.close();
                    catch(Exception e)
          }//finally
          return userList;
    }/userList
    }//userservices4--------------------------User4.java ( A bean Class )
    package com.xyz;
    import java.io.*;
    import java.util.*;
    public class User4
         public User4(){}
              public void setT1(String s)
                    T1=s;
               public String getT1()
                    return T1;
               public void setT2(String s)
                    T2=s;
               public String getT2()
                    return T2;
               public void setO1(String s)
                         O1=s;
                    public String getO1()
                         return O1;
               public void setO2(String s)
                          O2=s;
                     public String getO2()
                          return O2;
           private String T1,T2;
           private String O1,O2;
    }-----------------------------form5.jsp
    <%@ page import= "java.io.* "%>
    <%@ page import= "java.sql.*" %>
    <%@ page import= "java.util.*" %>
    <%@ page import= "javax.servlet.http.*" %>
    <%
    ArrayList userList = (ArrayList)request.getAttribute("userList");
    out.println(userList);
    %>=============================
    PLZ HELP ME

    weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:213)Deepali, your question is about weblogic. I would suggest that you post your question to the bea forums at http://forums.bea.com.
    It seems that you misunderstood the name of this forum, "Application Server - General". There are many forums in this "Application Server" catagory. Each of them concentrates on one aspect of Oracle Application Server. This forum is for the "General" questions, the questions that do not readily belong to the those forums but still concerns with OAS,.

  • Route add problem in solaris 10 zone

    hi all
    when i add route in one of my solaris 10 zone.. i get the following error. any workaround?
    # route add xxx.xxx.255/24 10.xxx.xxx.1
    add net xxx.xxx.255/24: gateway 10.xxx.xxx.1: insufficient privileges
    thanks
    peter

    it means i can only add route in globle zone? but
    global zone and sub-zones are using diff IP and
    interface cards. so how?But they're children of the same kernel. There can only be one routing table (at the moment, anyway). So make your route adds from global and watch them appear in the netstat output of your non-global zones.
    I agree that this is a confusing and poorly documented aspect of zones, however. I will admit to you that I barely understand it myself. However, there is a good answer to a question I had about this in comp.unix.solaris. Search that newsgroup for "Viewing non-global routes from global zone". A similar question fell on deaf ears here.
    Also, I would recommend searching this forum for "zone routes" or "zone routing" as this is a frequently hit topic.
    --gc1973                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem with ArrayList

    Hello,
    I am having a problem with a program I am trying to write. The idea of the program is to:
    A) read a list of movies list from a text file
    B) create an object for each movie using the information from the text file
    C) place the objects into an arrayList
    My problem is that when I check my arrayList it seems to only contain multiple copies of the first movie read from the text file. Here is my code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    public class MovieReader
         PrintWriter outputStream = null;
         public void readFile()
              try
                      BufferedReader in = new BufferedReader(new FileReader("movie.txt"));
                      String str;
                      while ((str = in.readLine()) != null)
                           process(str);
                      in.close();
              catch (IOException e)
                  e.printStackTrace();
         ArrayList <ValidMovie> movieList = new ArrayList<ValidMovie>();
         private void process(String line)
              String[] array = line.split("\t");
              int i = 0;
              for ( i = 0; i < array.length; i++)
                   String tempTitle = array[0];
                   String tempYear = array [1];
                   String tempRating = array [2];
                   String tempFormat = array [3];
                   ValidMovie uuj = new ValidMovie(tempTitle, tempYear, tempRating, tempFormat);
                   movieList.add(uuj);
              System.out.println("item at index 1 is:   " + movieList.get(1));
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         private void writeFile(String [] arrayL)
              String [] arrayWrite = arrayL;
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
         public static void main(String[] args)
              MovieReader mv = new MovieReader();
              mv.readFile();
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    }This is the code that creates an object for each movie:
    import java.io.Serializable;
    public class ValidMovie implements Serializable
         private String title;
         private String year;
         private String rating;
         private String format;
         public ValidMovie()
         public ValidMovie(String tTitle, String tYear, String tRating, String tFormat)
              title = tTitle;
              year = tYear;
              rating = tRating;
              format = tFormat;
         //Getters for title, year, rating and format
         public String getTitle ()
              return title;
         public String getYear ()
              return year;
         public String getRating ()
              return rating;
         public String getFormat ()
              return format;
         public String toString ()
              return title + "\t" + year + "\t" + rating + "\t" + format;
    }The following is what I have in the movie.txt file:
    Bamboozled     2000     2     DVD
    What Lies Beneath     2000     1.5     DVD
    Beneath the Planet of the Apes     1970     1     DVD
    You Can Count On Me     2000     3.5     Theater
    And finally this is the result when I run the code:
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    I am sure that it is something simple that I am overlooking but I cannot figure it out. When I change the index in the code:
    System.out.println("item at index 1 is:   " + movieList.get(1));to 0 or 2 or 3 then result is the same, it will just show the first movie in the text file. Any help would be greatly appreciated. Thanks

    Thanks for the reply, it helped but I am now getting 4 of each of the movies after adding you suggestion. This is much better now I just need to figure out why the loop is causing the extra copies. Thanks again :)
    Item 0: Bamboozled     2000     2     DVD
    Item 1: Bamboozled     2000     2     DVD
    Item 2: Bamboozled     2000     2     DVD
    Item 3: Bamboozled     2000     2     DVD
    Item 4: What Lies Beneath     2000     1.5     DVD
    Item 5: What Lies Beneath     2000     1.5     DVD
    Item 6: What Lies Beneath     2000     1.5     DVD
    Item 7: What Lies Beneath     2000     1.5     DVD
    Item 8: Beneath the Planet of the Apes     1970     1     DVD
    Item 9: Beneath the Planet of the Apes     1970     1     DVD
    Item 10: Beneath the Planet of the Apes     1970     1     DVD
    Item 11: Beneath the Planet of the Apes     1970     1     DVD
    Item 12: You Can Count On Me     2000     3.5     Theater
    Item 13: You Can Count On Me     2000     3.5     Theater
    Item 14: You Can Count On Me     2000     3.5     Theater
    Item 15: You Can Count On Me     2000     3.5     Theater

  • Problems with sort, search and write objects o an ArrayList

    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that.
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(
    Any ideas?
    Thank you!
    Anton

    lavalampan wrote:
    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that. Create a custom comparator.
    >
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.Implement hashCode and equals.
    >
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(Depends on what your requirement is, but yes, Serialization might work for you. Your classes should in that case implement Serializable.
    Kaj

  • ArrayList prob

    Hi,
    Im trying to create a program which deals with stats for a football team. I have a class Player containing games played and goals scored which externds from a Class Person which contains details such as Name, DoB ,height etc.
    I am trying to store my players in an Arraylist so i can use Comparable to change the order of the list e,g( by name, by games played, by goals scored.)
    However, using the BlueJ environment i get i get a compiler error : Using unsafe or unchecked operations on the ArrayList.add line, and a Null exception when running the following code:
    import java.util.*;
    public class Club
        private String clubName;
        private String name;
        private String surname;
        private int ageInYears;
        private int heightInCm;
        private int weightInKg;
        private int goals;
        private int games;
        private ArrayList playerList;
        public Club(String clubName)   
         this.clubName= clubName;
         ArrayList<Player> playerList =  new ArrayList<Player>();
        public void addPlayer(String name,String surname,int ageInYears,int heightInCm,int weightInKg,int goals, int games)
            this.name= name;
            this.surname= surname;
            this.ageInYears= ageInYears;
            this.heightInCm= heightInCm;
            this.weightInKg= weightInKg;
            this.goals= goals;
            this.games= games;
            playerList.add(new Player(name,surname,ageInYears,heightInCm,weightInKg,goals,games));
            int z= playerList.size();
            System.out.println(z);
    }Many thanks for any help or suggestions

    but I still get a null pointer exception at the line
    playerList.add(new Player(name,surname,ageInYears,heightInCm,weightInKg,goals,games));The only scenario I can think of for a NullPointerException to be thrown by this statement is that playerList is null...
    (And I can't understand how something could actually be added in the list in this case...)
    Are you sure the exception is thrown at this line? Maybe you could post updated code, and the stack trace.
    On another note, I have a class Goalkeeper which extends from Player ( which has extended from person).
    Will I be able to add a Goalkeeper into the List even though it expects an Player object?You can add any instance of Player or subclass of Player, so it won't be a problem to add goalkeepers. (Did you try?)
    (a Goalkeeper is a Player)

  • Applying brute force on a huge problem

    hi guys ,
    i m kinda stuck with this ..
    this is a project euler problem ... the problem is this
    The following iterative sequence is defined for the set of positive integers:
    n &#8594; n/2 (n is even)
    n &#8594; 3n + 1 (n is odd)
    Using the rule above and starting with 13, we generate the following sequence:
    *13 &#8594; 40 &#8594; 20 &#8594; 10 &#8594; 5 &#8594; 16 &#8594; 8 &#8594; 4 &#8594; 2 &#8594; 1*
    It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
    Which starting number, under one million, produces the longest chain?
    NOTE: Once the chain starts the terms are allowed to go above one million.
    i just went for straightforward bruteforce approach ...
    heres my code
    import java.io.*;
    import java.util.*;
    public class pro14
         public static void main(String args[])
              int j=0,pos=0;
                    int upperlimit=1000000;
              ArrayList<Integer> temp = new ArrayList<Integer>();
              ArrayList<Integer> longest = new ArrayList<Integer>();
              for(int i=1;i<upperlimit;i++)
                   temp.add(new Integer(i));
                   j=i;
                   while(j!=1)
                       if(j%2==0)
                           j=j/2;      
                          else
                               j=3*j+1;
                         temp.add(new Integer(j));
                    if(longest.size() < temp.size())
                         longest.clear();
                         for(int k=0;k<temp.size();k++)
                             longest.add(temp.get(k));               
                        pos=i;
                    temp.clear();          
            System.out.println("The starting number that produces longest chain="+pos);   
            for(int i=0;i<longest.size();i++)
                System.out.print(longest.get(i)+"->");
    {code}the above code works for 100,1000,10000,100000 but not a million ... for example if i change upperlimit variable to 100000 (hundred thousand) i get the output as
    {code:java}
    The starting number that produces longest chain=77031
    77031->231094->115547->346642->173321->519964->259982->129991->389974->194987->584962->292481->877444->438722->219361->658084->329042->164521->493564->246782->123391->370174->185087->555262->277631->832894->416447->1249342->624671->1874014->937007->2811022->1405511->4216534->2108267->6324802->3162401->9487204->4743602->2371801->7115404->3557702->1778851->5336554->2668277->8004832->4002416->2001208->1000604->500302->250151->750454->375227->1125682->562841->1688524->844262->422131->1266394->633197->1899592->949796->474898->237449->712348->356174->178087->534262->267131->801394->400697->1202092->601046->300523->901570->450785->1352356->676178->338089->1014268->507134->253567->760702->380351->1141054->570527->1711582->855791->2567374->1283687->3851062->1925531->5776594->2888297->8664892->4332446->2166223->6498670->3249335->9748006->4874003->14622010->7311005->21933016->10966508->5483254->2741627->8224882->4112441->12337324->6168662->3084331->9252994->4626497->13879492->6939746->3469873->10409620->5204810->2602405->7807216->3903608->1951804->975902->487951->1463854->731927->2195782->1097891->3293674->1646837->4940512->2470256->1235128->617564->308782->154391->463174->231587->694762->347381->1042144->521072->260536->130268->65134->32567->97702->48851->146554->73277->219832->109916->54958->27479->82438->41219->123658->61829->185488->92744->46372->23186->11593->34780->17390->8695->26086->13043->39130->19565->58696->29348->14674->7337->22012->11006->5503->16510->8255->24766->12383->37150->18575->55726->27863->83590->41795->125386->62693->188080->94040->47020->23510->11755->35266->17633->52900->26450->13225->39676->19838->9919->29758->14879->44638->22319->66958->33479->100438->50219->150658->75329->225988->112994->56497->169492->84746->42373->127120->63560->31780->15890->7945->23836->11918->5959->17878->8939->26818->13409->40228->20114->10057->30172->15086->7543->22630->11315->33946->16973->50920->25460->12730->6365->19096->9548->4774->2387->7162->3581->10744->5372->2686->1343->4030->2015->6046->3023->9070->4535->13606->6803->20410->10205->30616->15308->7654->3827->11482->5741->17224->8612->4306->2153->6460->3230->1615->4846->2423->7270->3635->10906->5453->16360->8180->4090->2045->6136->3068->1534->767->2302->1151->3454->1727->5182->2591->7774->3887->11662->5831->17494->8747->26242->13121->39364->19682->9841->29524->14762->7381->22144->11072->5536->2768->1384->692->346->173->520->260->130->65->196->98->49->148->74->37->112->56->28->14->7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1->
    {code}so when i try the same for a million i get this
    {code:java}
    mintoo@mintoo pro14]$ java pro14
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
         at pro14.main(pro14.java:32)
    {code}i have even tried
    {code:java}
    java -Xms512m -Xmx2048m pro14
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
         at java.util.Arrays.copyOf(Arrays.java:2772)
         at java.util.Arrays.copyOf(Arrays.java:2746)
         at java.util.ArrayList.ensureCapacity(ArrayList.java:187)
         at java.util.ArrayList.add(ArrayList.java:378)
         at pro14.main(pro14.java:32)
    [mintoo@mintoo pro14]$
    {code}
    Edited by: mintoo2cool on Feb 8, 2010 4:10 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    mintoo2cool wrote:
    the above code works for 100,1000,10000,100000 but not a million ... for example if i change upperlimit variable to 100000 (hundred thousand) i get the output as You're also going to run into overflow problems if you're storing intermediate results using an int. The maximum value you can store in an integer variable is 2147483647, but if you run through the steps for the input number 113382 you'll see that about 120 steps in the calculated value (which is 2482111348) is greater than the maximum value you can store in the integer established above. So, what happens? Well, the actual value stored goes negative. So, once you have a negative number in your chain you're never coming back to positive and you'll end up with an infinite loop. This will probably be why you ran out of memory even after allocating a maximum of 2GB. Try using a long to store your intermediary values instead.

  • Sorting problem in TreeMap, please help urgent :-((

    Hi
    Following is a program, please execute it to see the problem. I am adding four elements in the TreeMap. The problem is when I add the elements it never compares the newly added element with the first element. I was sick of it so to test the TreeMap I created my own small class and defined a Comparator for that class. Following is the code which shows the problem in TreeMap. Am I doing something wrong? Please help its urgent.
    import java.util.*;
    public class SortingCollection {
         public static void main(String[] args) {
              SortingCollection sortingCollection = new SortingCollection();
              sortingCollection.sortingTest();
         public void sortingTest() {
              TreeMap treeMap = new TreeMap();
              treeMap.put(new Test("Bhushan", 1022), new Integer(1022));
              treeMap.put(new Test("Wasil", 1023), new Integer(1023));
              treeMap.put(new Test("Ifti", 1020), new Integer(1020));
              treeMap.put(new Test("Roshan", 1021), new Integer(1021));
              System.out.println(treeMap);
              Test test = new Test("Bhushan", 1028);
              treeMap.put(test, new Integer(1022));
              System.out.println(treeMap);
         public class Test implements Comparable {
              public String name;
              public int age;
              public Test(String name, int age) {
                   this.name = name;
                   this.age = age;
              public int compareTo(Object toBeCompared) {
                   Test casted = (Test) toBeCompared;
                   if (name.equals(casted.name)) {
                        System.out.println("Returning 0 for " + name + " " + casted.name);
                        return 0;
                   System.out.println("Returning -1 for " + name + " " + casted.name);
                   return -1;
              public String toString() {
                   return "[" + name + ", " + age + "]";
    }

    If you are using TreeMap, you should want the keys to be immutable. You can't change the state of the keys of a Map such that their natural order will change, or chaos will happen.
    If the key is the GateKeeperInfo class (which has host, port, and # of users as its data members) and the value is "some other object reference which you need", and this reference is closely tied to the GateKeeperInfo, have you considered making it a member of the GateKeeperInfo?
    That way you don't need this TreeMap business. You can have the natural ordering imposed on the GateKeeperInfo class (which is apparently comparing the host and port only). You can also have a Comparator object that can compare these objects in a different way (# of users, for instance).
    public class MyClass implements Comparable
       String host;
       int    port;
       int    currNumUsers;
       Object someOtherObjectReferenceINeed;
       // or if the object reference you need is an Integer, make that last member
       // an int...
       // Also, let's keep a Comparator in here for comparing # of users.
       // See further down for actual implementation...
       public static final Comparator BY_NUM_USERS = new NumUsersComparator();
         // Use the equal methods to determine whether or not host and port matches
       public boolean equals( Object obj )
       // Use the compareTo method to compare 2 instances in terms of host and port
       public int compareTo( Object obj )
         // Make this object take care of changing # of users, outside of the
         // Comparable interface.
         public int getNumUsers();
         public int bumpNumUsers( int byThisAmount ); // changes # of users...
         // Beef up this object to take advantage of someOtherObjectReferenceINeed
    // Use this Comparator object to compare 2 instances of MyClass
    // according to # of users.
    public class NumUsersComparator implements Comparator
         public int compare( Object a, Object b )
              MyClass left      = (MyClass)a;
              MyClass right      = (MyClass)b;
              // I am assuming both # of users are of the same sign...positive
              return ( right.getNumUsers() - left.getNumUsers() );
    // Now when you need to compare, you can do it 2 different ways...
    // You can use whatever Collection you fits, List, Set, ...
    // I am going to use List in this case
    List gateways = new ArrayList;
    // add the objects...
    gateways.add( /* . . . */ );
    // Now let's sort in terms of user/port
    Collections.sort( gateways );
    // Let's sort in terms of number of users...
    Collections.sort( gateways, MyClass.BY_NUM_USERS );
    // I am going to mix them around now...
    Collections.shuffle( gateways );
    // Now let's find the gateway w/ the largest # of users...
    MyClass currMaxGateway = Collections.max( gateways, MyClass.BY_NUM_USERS );
    .

  • Querying, then generating ArrayLists with variable names

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

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

  • ArrayList Error on Index

    This is my code;
    * Main2.java
    * Created on 09 February 2007, 14:40
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package testing;
    * @author Administrator
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.ListIterator;
    * @author Administrator
    public class Main2 {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rsBankName=null;
        int valid,invalid,total;
        /** Creates a new instance of Main */
        public Main2() {
            connectOracle();
            readCards(2007,1,31);
            //System.out.println(checkDate(""));
         * @param args the command line arguments
        public void connectOracle(){
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@IP:SID", "user", "pwd");
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {}
        public void readCards(int year,int month,int day){
            String bankCode="";
            ArrayList<String> bname=new ArrayList<String>(10);
            try {
                rsBankName=stmt.executeQuery("select bank_code,bank_name from bank");
                rsBankName.first();
                do{
                    bname.add(rsBankName.getInt("bank_code"),rsBankName.getString("bank_name"));
                }while(rsBankName.next());
            } catch (SQLException ex) {
                ex.printStackTrace();
            ListIterator li=bname.listIterator();
            while(li.hasNext()){
                System.out.println(li.next());
        public static void main(String[] args) {
            new Main2();
    }And I am getting this Stack trace
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.add(ArrayList.java:367)
    at testing.Main2.readCards(Main2.java:60)
    at testing.Main2.<init>(Main2.java:36)
    at testing.Main2.main(Main2.java:71)
    I search for it on the net, it say it has a bug and it was version 1.2 and I am using the new version of JDK 1.6.
    Any idea what is going wrong.

    D'OH!!
    You can't add an element at a specific index unless
    there is already something at that index ? WTF? This
    is strange behavior, What is even odder is that you can expand by one with "add", just not greater than that.
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 0; i< 10; i++ ) {
             thingies.add( i, i );
         System.out.println( thingies );works, but
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 9; i>0; i-- ) {
             thingies.add( i, i );
         System.out.println( thingies );does not.
    even though I will say that
    there are other classes you could use instead. Try a
    HashMap<Integer,String> Or if the size is fixed, use an array.

  • Wireless problem since the "pros" are answering on June 2nd come and answer this

    How is there not a recall for this line especially the older ones. Here is my justifiable reason and if anyone else has the same problems key in because the "pros" are looking for today and yesterday only. Then they can't deny that they don't know of any problems with this line.
    Well let's begin.
         So you might not admit it buy you most definitely know that there are numerous problems with the tx1000 line. Multiple complaints about people not having wifi work. A little less that have constant BSOD. Some booting black screens. Fingerprint stops working etc.
         Well mine is wifi does not work. It hasn't been working since 2-3 years ago, just never got enough time to troubleshoot and complain.
         The problems are so widespread that there is even the "hair dryer" trick which I did not try. That is how widespread it is. Maybe you might know of another product that has a trick to it that involves a towel? Yeah that's right another product rid with problems, the Xbox 360. But unlike HP Microsoft has admit to their problems and have extended their warranty as well as refund people who have paid. .
         I have complained once every year to see if you finally have a recall but never do. I actually never troubleshooted using your steps before because I just didn't have the time. Well since now I have the time, I have decided to do some major testing. I have bought another laptop obviously not HP. It has a Intel 5300 AGN. So what good way to test than to do some swapping. Put in your broadcam wireless into my other laptop. In 2 seconds Windows Generic Drivers install and get it working. Put in Intel 5300 AGN in the tx1000. Um.... yeah doesn't even notice a new card was installed and still have the amber light. Play around installing drivers for it HP Wireless Assistant. Anything. Even updated the Bios. Nothing makes it work while on my other laptop it works perfectly fine. Not just the Intel 5300 AGN but the wireless card that was in the tx1000. What does this mean? It is a board problem which makes sense because the only reason why people could be losing fuctions one by one such as wireless, fingerprint read, SD card reader and come up with Black Screen booting and constant BSOD is a mobo problem. Why haven't HP recalled this line and treat their customers like customers? I don't know but with a move like this they put many previous customers to stop recommending them. I currently have 2 HP Desktops an HP Printer and this tx1000. The 2 desktops broke one way or another. Thankfully both still in warranty which they then are forced to repair. HP Printer works fine which is a miracle. Not a great printer though.
        By the way anyone know what the first result is for google when you type tx1000 and see the list. Drumroll......
     -tx1000 recall
     -tx1000
     -tx1000 motherboard
     -tx1000 specs
     -tx1000 wireless card problems
     -tx1000 problems
        What do you know don't you think its odd for this laptop that recall tops everything even tx1000 itself and tx1000 specs. Followed by motherboard probably people looking for a replacement motherboard. And after specs is wireless card problems that is guess what, the problem I have. Followed by the general tx1000 problems.
        Because of this I have stopped recommending HPs which I have recommended for a long time especially on the printer side. People ask me Dell or HP and I would tell them HP now I say do you have to choose between those two? If you do then go with Dell but ASUS are making some great laptops. For printers I have started recommending EPSON, which I just love their Artisan line.
        To show you how widespread this is I have attached a petiton which I did not start but I found.
    http://www.ipetitions.com/petition/hp_tx1000_problems/
    If you have problems with this line sign the petition even though I am 99% sure it won't do anything. But it will just show others what kind of company HP is. Better yet though reply to this on HPs own forum to show the problems of their tx1000 line
    At the time of this posting there are 224 complaints and remember those are just people who found the petition and actually signed it thinking it would have done something. Most probably found it but didn't even bother because what would an online petition do right?
    /end rant
    Well if you read all this Thank You for your time I guess.
    Haha tried to add problems to tags and they don't allow it. What is that?
    Bunch of links to problems of same kind posted on HP forums.
    http://h30434.www3.hp.com/t5/TX-TM-Series-Notebooks/Missing-WIFI-and-Increasing-Heat-from-tx1320us-t...
    http://h30434.www3.hp.com/t5/TX-TM-Series-Notebooks/Why-is-there-no-TX1000-recall/td-p/140683
    http://h30434.www3.hp.com/psg/board/message?board. id=Hardware&thread.id=5789
    http://h30434.www3.hp.com/psg/board/message?board. id=Hardware&thread.id=1867
    http://h30434.www3.hp.com/psg/board/message?board. id=Hardware&message.id=1867&query.id=631242#M1867
    http://forums13.itrc.hp.com/service/forums/bizsupp ort/categoryhome.do?categoryId=411
    http://h30434.www3.hp.com/t5/TX-TM-Series-Notebooks/TX-1000-does-not-start/td-p/169566

    Hmmm lets see 3900 have signed the petition. At say $1500 for each computer. Thats about $585,000! I wonder how much the recall would cost?  VS. http://www.youtube.com/watch?v=ctHTF3oNdxI HP Got your money that do not care about there customers or support. Best thing you can do is keep an eye out for a class action suit and try the penny fix.
    http://www.classcounsel.com/news/hpzd.html
    A Settlement was reached between Nvidia and HP however all the TX1000 owners get the shaft. HP another Big Business ruining this country!

  • Reading a file into ArrayList??

    HI,
    I have the following code which saves data that I have in my ArrayList to a file.
    How can I read this data back into the array?
    What would the code be?
    I have searched for a solution to this for a while but can't understand how to do it.
    Please help me.
              if (e.getSource() == saveBtn)
              try
                   //Create file and object output streams
                   outputBook = new FileOutputStream("Books1.ser",true);
                   objSaveBook = new ObjectOutputStream(outputBook);
                        catch(Exception error)
                   System.err.println("Error outputting file");
              try
              strTitle = txtTitle.getText();
              strDesc = txtDesc.getText();
              strAuthor = txtAuthor.getText();
              strGenre = txtGenre.getText();
              ArrayList arraylist = new ArrayList();
                   arraylist.add(strTitle);
                   arraylist.add(strAuthor);
                   arraylist.add(strDesc);
                   arraylist.add(strGenre);
                   objSaveBook.writeObject(arraylist);
                   objSaveBook.flush();
                   txtTitle.setText("");
                   txtDesc.setText("");
                   txtAuthor.setText("");
                   txtGenre.setText("");
                   txtTitle.requestFocus();
                   objSaveBook.close(); //Close the object output stream
                   outputBook.close();
              catch(Exception error)
                   System.err.println("Error writing to file");
              }The save objects are like this:
                   inputBook = new FileInputStream("Books1.ser");
                   objGetBook = new ObjectInputStream(inputBook);

    I know it goes like this
    public ArrayList<String> readFromFile(String fileName) {
        ArrayList<String> ret = new ArrayList<String>();
        LineNumberReader in = new LineNumberReader(new FileReader(fileName));
        String line;
        while((line = in.readLine()) != null)
            ret.add(line);
        in.close();
        return ret;
    }But where do I put what?

  • Stupid ArrayLists... or is it me?!

    I have this code in my enqueue class:
         int newNode = (_queue.size() + 1);
         _queue.ensureCapacity( newNode );
         _queue.add( newNode, node );
    node is my own node class and queue is defined as ArrayList queue = new ArrayList();
    I'm getting a runtime error saying I'm out of bounds:
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.add(ArrayList.java:367)
    at MinBinaryHeapPriorityQueue.enqueue(MinBinaryHeapPriorityQueue.java:82)
    How can I resize the ArrayList? I thought it did that automatically? I have to use ArrayList, so no other DTs or Classes.
    Anyone? I've tried changing just about everything. newNode, and ensureCapacity(+alot), I've even constructed ArrayList with (100).
    I've also tried taking the ensureCapacity line out and get the same thing... Any thing else that could help?
    NOMAD

         int newNode = (_queue.size() + 1);
         _queue.ensureCapacity( newNode );The indexes of an ArrayList start at 0 so here
         _queue.add( newNode, node );you are trying to add an element at an index beyond the limit of your list.
    The line should be:
    _queue.add(newNode - 1, node);
    or
    queue.add(queue.size(), node);
    And the above is the same as:
    _queue.add(node);

Maybe you are looking for