Declaring Arraylist

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

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

Similar Messages

  • Can we declare arrayList as variable ??

    Hi,
    Can we declare arrayList as variable ???
    Help me regarding this....
    Thanks in advance

    Plz can u show me with example....ArrayList al = new ArrayList().
    http://www.google.co.in/search?hl=en&safe=off&q=ArrayList+Java&btnG=Search&meta=

  • Can I declare arraylists in data transfer object

    Can I use arraylists in data transfer objects

    Yes, and don't double post:
    http://forum.java.sun.com/thread.jsp?thread=540027&forum=425&message=2616354
    Answers don't always come in three minutes. Be patient.

  • Simple ArrayList declaration will NOT compile in Eclipse

    For some reason I can't get the following line of code to compile in eclipse, even though the exact same code compiles in NetBeans.
    I'm trying to work on my program at school and they don't have Netbeans installed they only have Eclipse so I have to work with it instead.
    Anyway, here's the line, it's a simple arraylist declaration:
    ArrayList<Integer> list = new ArrayList<Integer>();I''ve got java.util.ArrayList imported.
    There error I get is the following:
    "Syntax error on token '<', invalid assignment operator.
    Can anyone clear this up for me, I've been searching and I've basically wasted a good half-hour without even touching my damn program.

    endasil wrote:
    well, to go higher than 1.4 you'd need a JDK that is higher than 1.4. It really has nothing to do with eclipse, and if you don't have a 1.5 jdk installed, NetBeans will have the same problem.Nonsense. Eclipse has it's own compiler, your JDK is irrelevant.
    Go to Window->Preferences->Java->Compiler and change the compiler compliance setting to 5.0 or higher. Your JRE will need to match, but the JDK need not even be installed

  • How to pick up values of particular tag from XMl file & store into an array

    Hi , i m using sax parser to read below xml file.
    <dvd-list>
    <dvd>
    <id>001</id>
         <title>Bollywood</title>
         <name>Lord of the rings</name>
         <length>150</length>
         <actor>Jonathan Austin</actor>
         <actor>Nicole Kidman</actor>
    </dvd>
    <dvd>
    <id>002</id>
         <title>Hollywood</title>
         <name>Taare Zamin pe</name>
         <length>200</length>
         <actor>Amir Khan</actor>
         <actor>Darsheel</actor>
    </dvd>
    <dvd>
    <id>003</id>
         <title>Bollywood</title>
         <name>Matrix reloaded</name>
         <length>150</length>
         <actor>Mickel</actor>
         <actor>Hally Berry</actor>
    </dvd>
    </dvd-list>
    & i want to store it into an arraylist .
    I declared arraylist a class var .
    i want to store all ids into an arraylist ...
    below is my code public void endElement (String namespaceURI, String localName, String qName, Attributes atts)
        throws SAXException
             if(qName.equals("id"))
       for (int i = 0; i < atts.getLength (); i++) {
                    list.add(i,atts.getValue (i));
           // showData ("</"+qName+">");
        }not working ... plz help me in this regard
    thanks a lot

    thanks , my id tag has no attribute...
    but sir again i m facing 1 problem
    to pick up values of tag i wrote below code public void startElement (String namespaceURI, String localName, String qName, Attributes atts)
        throws SAXException
             System.out.println("localName"+qName);
             str=qName;
        public void characters (char buf [], int offset, int len)
        throws SAXException
             String s = new String(buf, offset, len);
          System.out.println("char>>"+s);
          s.trim();
          if(str.equals("id"))
               list.add(s);
              if(str.equals("name"))
                   list.add(s);
              if(str.equals("title"))
                   list.add(s);
              if(str.equals("length"))
                   list.add(s);
              if(str.equals("actor"))
                   list.add(s);   
        public void endElement (String namespaceURI, String localName, String qName, Attributes atts)
        throws SAXException
        }here my list size shud be 5 ideally but it is showing 30!!!!
    also debug stmt sysout(char>>+s); is showing series of
    char>> ...it means charactes(0 method is being called several times ...while my xml contains
    <dvd-list>
    <dvd>
    <id>001</id>
         <title>Bollywood</title>
         <name>Lord of the rings</name>
         <length>150</length>
         <actor>Jonathan Austin</actor>
    </dvd>
    </dvd-list>
    plz help me in this regard to understand this flow....
    thanks a lot in advance

  • Problem with Collections.binarySearch()

    public class TaxPayerRecord implements Comparable <TaxPayerRecord>
    private String nric;
    private String name;
    private String dateOfBirth;
    private String gender;
    private String blockNo;
    private String unitNo;
    private String streetName;
    private String bldgName;
    private String postalCode;
    private long totalIncome;
    private long totalDonation;
    private long totalPersonalRelief;
    * Creates a new instance of TaxPayerRecord
    public TaxPayerRecord(String nric, String name, String dateOfBirth, String gender,
                   String blockNo, String unitNo, String streetName, String bldgName,
                   String postalCode, long totalIncome, long totalDonation,
                   long totalPersonalRelief)
    this.nric = nric;
    this.name = name;
    this.dateOfBirth = dateOfBirth;
    this.gender = gender;
    this.blockNo = blockNo;
    this.unitNo = unitNo;
    this.streetName = streetName;
    this.bldgName = bldgName;
    this.postalCode = postalCode;
    this.totalIncome = totalIncome;
    this.totalDonation = totalDonation;
    this.totalPersonalRelief = totalPersonalRelief;
    public String toString()
    return nric+"|"+name+"|"+dateOfBirth+"|"+gender+"|"+blockNo+"|"+unitNo+"|"+streetName+"|"+
    bldgName+"|"+postalCode+"|"+totalIncome+"|"+totalDonation+"|"+
    totalPersonalRelief;
    public long getTotalIncome()
    return totalIncome;
    public long getTotalDonation()
    return totalDonation;
    public long getTotalPersonalRelief()
    return totalPersonalRelief;
    public String getDateOfBirth()
    return dateOfBirth;
    public String getPostalCode()
    return postalCode;
    public int compareTo (TaxPayerRecord next)
              return this.nric.compareTo(next.nric);
    } //TaxPayerRecord
    import java.io.*;
    import java.util.*;
    public class TaxPayerProgramme
         public TaxPayerProgramme()
                             String menu = "Options: \n"
                                            + "1. Compute And Print List Of Tax Payers (Sorted by NRIC) \n"
                                            + "2. Compute And Summary Of Tax Revenue \n"
                                            + "3. Search for Tax Payer by NRIC \n"
                                            + "Enter option(1-2,0 to quit): ";
                             System.out.print(menu);
                             Scanner input = new Scanner( System.in );
                             int choice = input.nextInt();
                             System.out.println("");
                        // Declaration
                             ArrayList<TaxPayerRecord> list = new ArrayList<TaxPayerRecord>();
                             String inFile ="TaxPayer2005.txt";
                             String line = "";
                             String nric;
                             String name;
                             String dateOfBirth;
                             String gender;
                             String blockNo;
                             String unitNo;
                             String streetName;
                             String bldgName;
                             String postalCode;
                             long totalIncome;
                             long totalDonation;
                             long totalPersonalRelief;
                        try{
                             //Read from file
                             FileReader fr = new FileReader (inFile);
                             BufferedReader inFile1= new BufferedReader (fr);
                        line=inFile1.readLine();
                                       while (line!=null)
                                       StringTokenizer tokenizer = new StringTokenizer(line,"|");
                                       nric=tokenizer.nextToken();
                                       name=tokenizer.nextToken();
                                       dateOfBirth=tokenizer.nextToken();
                                       gender=tokenizer.nextToken();
                                       blockNo=tokenizer.nextToken();
                                       unitNo=tokenizer.nextToken();
                                       streetName=tokenizer.nextToken();
                                       bldgName=tokenizer.nextToken();
                                       postalCode=tokenizer.nextToken();
                                       totalIncome=Long.parseLong(tokenizer.nextToken());
                                       totalDonation=Long.parseLong(tokenizer.nextToken());
                                       totalPersonalRelief=Long.parseLong(tokenizer.nextToken());
                                       TaxPayerRecord person = new TaxPayerRecord(nric,name,dateOfBirth,gender,blockNo,unitNo,
                                                                                              streetName,bldgName,postalCode,totalIncome,
                                                                                              totalDonation,totalPersonalRelief);
                                       list.add(person);
                                       line=inFile1.readLine();
                                       }//end while
                        inFile1.close();
                             }// end try
                        catch (Exception e)
                             e.printStackTrace();
                        }//end catch
                        do{
                                  switch(choice)
                                       case 0:
                                       System.exit(0);
                                       break;
                                       case 1:
                                       // run list
                                       printList(list);
                                       break;
                                       case 2:
                                       printSummary(list);
                                       break;
                                       case 3:
                                       search(list,input);
                                       break;
                                  }//end switch
                             System.out.print(menu);
                             choice = input.nextInt();
                             System.out.println("");
                             }// end do
                             while(choice !=0);
                             Collections.sort(list);
         }//end TaxPayerProgramme()
         private void total(ArrayList<TaxPayerRecord> list)
              // Declaration
              double total=0;
              // calculate total
                   for (int i=0; i<list.size(); i++)
                   total=+ tax(i,list);
              //print msg
              System.out.println("Total revenue collectable for year 2006 (S$): "+total+"\n");
         private double tax(int i,ArrayList<TaxPayerRecord> list)
              // Declaration
              double income;
              double tax;
              // calculate income
              income =list.get(i).getTotalIncome()-list.get(i).getTotalDonation()
                        -list.get(i).getTotalPersonalRelief();
              // calculate tax
                   if (income>320000)
                        tax=(((income-320000)*0.21)+44850);
                   else if (income>160000)
                        tax=(((income-160000)*0.18)+16050);
                   else if (income>80000)
                        tax=(((income-80000)*0.145)+4450);
                   else if (income>40000)
                        tax=(((income-40000)*0.0875)+950);
                   else if (income>30000)
                        tax=(((income-30000)*0.0577)+375);
                   else
                        tax=((income-20000)*0.0577);
              return tax;
         private void totalAge(ArrayList<TaxPayerRecord> list)
                   // Declaration
                   String msg;
                   int i,age;
                   double grp1=0;
                   double grp2=0;
                   double grp3=0;
                   double grp4=0;
                   // calculate revenue by age
                        for (i=0; i<list.size(); i++)
                        age= 2006- Integer.parseInt(list.get(i).getDateOfBirth().substring(6,list.get(i).getDateOfBirth().length()));
                        if (age>55)
                             grp4 =+ tax(i,list);
                        else if (age>35)
                             grp3 =+ tax(i,list);
                        else if (age>17)
                             grp2 =+ tax(i,list);
                        else
                             grp1 =+ tax(i,list);
                   //print msg
                   msg="Total revenue by age range (S$) \n"+
                        "\t"+"(1 to 17)"+"\t"+ grp1 +"\n"     +
                        "\t"+"(18 to 35)"+"\t"+ grp2 +"\n"     +
                        "\t"+"(36 to 55)"+"\t"+ grp3 +"\n"     +
                        "\t"+"(above 55)"+"\t"+ grp4 +"\n";
                   System.out.println(msg);
    private void totalDistrict(ArrayList<TaxPayerRecord> list)
                   int count=1;
                   double temp=0;
                   double [][] array = new double [list.size()][2];
                        for (int i=0; i<list.size(); i++)
                        array[0]=Double.parseDouble(list.get(i).getPostalCode().substring(0,2));
                        array[i][1]=tax(i,list);
                   System.out.println("Total revenue by district (S$) ");
                        do{
                                  for (int a=0; a<list.size(); a++)
                                       if (count == array[a][0] )
                                       temp=array[a][1];
                                  }//end for loop
                             System.out.print("\t"+"(district "+count+")"+"\t"+ temp +"\n");
                             temp=0;
                             count++;
                        }while(count!= 80);// end of do_while loop
              System.out.print("\n");
         private void printList(ArrayList<TaxPayerRecord> list)
              System.out.println("List of Tax Payers fpr Year 2006");
                   for (int i=0; i<list.size(); i++)
                   System.out.println((i+1)+") "+list.get(i)+"|"+tax(i,list)+"\n");
         private void printSummary(ArrayList<TaxPayerRecord> list)
                   total(list);
                   totalAge(list);
                   totalDistrict(list);
         private void search(ArrayList<TaxPayerRecord> list,Scanner input)
                   String nric;
                   int value;
                   System.out.print("Enter NRIC Number: ");
                   nric = input.next();
                   Collections.sort(list);
                   value = Collections.binarySearch(list,nric);
         public static void main(String [] args)
                   new TaxPayerProgramme();
    I keep getting this message:
    C:\Documents and Settings\Xiong\Desktop\TaxPayerProgramme.java:285: cannot find symbol
    symbol : method binarySearch(java.util.ArrayList<TaxPayerRecord>,java.lang.String)
    location: class java.util.Collections
                   value = Collections.binarySearch(list,nric);
                   ^
    1 error
    Tool completed with exit code 1

    You can't search a list of TacPayerRecords using a String.

  • Need Help With Collection.binarySearch ! Please help me

    * TaxPayerRecord.java
    * Created on December 21, 2006, 11:42 AM
    public class TaxPayerRecord implements Comparable <TaxPayerRecord>
        private String nric;
        private String name;
        private String dateOfBirth;
        private String gender;
        private String blockNo;
        private String unitNo;
        private String streetName;
        private String bldgName;
        private String postalCode;
        private long totalIncome;
        private long totalDonation;
        private long totalPersonalRelief;
         * Creates a new instance of TaxPayerRecord
        public TaxPayerRecord(String nric, String name, String dateOfBirth, String gender,
                                 String blockNo, String unitNo, String streetName, String bldgName,
                                 String postalCode, long totalIncome, long totalDonation,
                                 long totalPersonalRelief)
            this.nric = nric;
            this.name = name;
            this.dateOfBirth = dateOfBirth;
            this.gender = gender;
            this.blockNo = blockNo;
            this.unitNo = unitNo;
            this.streetName = streetName;
            this.bldgName = bldgName;
            this.postalCode = postalCode;
            this.totalIncome = totalIncome;
            this.totalDonation = totalDonation;
            this.totalPersonalRelief = totalPersonalRelief;
        public String toString()
            return nric+"|"+name+"|"+dateOfBirth+"|"+gender+"|"+blockNo+"|"+unitNo+"|"+streetName+"|"+
                   bldgName+"|"+postalCode+"|"+totalIncome+"|"+totalDonation+"|"+
                   totalPersonalRelief;
        public long getTotalIncome()
            return totalIncome;
        public long getTotalDonation()
            return totalDonation;
        public long getTotalPersonalRelief()
            return totalPersonalRelief;
        public String getDateOfBirth()
            return dateOfBirth;
        public String getPostalCode()
            return postalCode;
        public int compareTo (TaxPayerRecord next)
              return this.nric.compareTo(next.nric);
    } //TaxPayerRecord
    import java.io.*;
    import java.util.*;
    public class TaxPayerProgramme
         public TaxPayerProgramme()
                             String menu = "Options: \n"
                                            + "1. Compute And Print List Of Tax Payers (Sorted by NRIC) \n"
                                            + "2. Compute And Summary Of Tax Revenue \n"
                                            + "3. Search for Tax Payer by NRIC \n"
                                            + "Enter option(1-2,0 to quit): ";
                             System.out.print(menu);
                             Scanner input = new Scanner( System.in );
                             int choice = input.nextInt();
                             System.out.println("");
                         // Declaration
                             ArrayList<TaxPayerRecord> list = new ArrayList<TaxPayerRecord>();
                             String inFile ="TaxPayer2005.txt";
                             String line = "";
                             String nric;
                             String name;
                             String dateOfBirth;
                             String gender;
                             String blockNo;
                             String unitNo;
                             String streetName;
                             String bldgName;
                             String postalCode;
                             long totalIncome;
                             long totalDonation;
                             long totalPersonalRelief;
                        try{
                             //Read from file
                             FileReader fr = new FileReader (inFile);
                             BufferedReader inFile1= new BufferedReader (fr);
                             line=inFile1.readLine();
                                       while (line!=null)
                                       StringTokenizer tokenizer = new StringTokenizer(line,"|");
                                       nric=tokenizer.nextToken();
                                       name=tokenizer.nextToken();
                                       dateOfBirth=tokenizer.nextToken();
                                       gender=tokenizer.nextToken();
                                       blockNo=tokenizer.nextToken();
                                       unitNo=tokenizer.nextToken();
                                       streetName=tokenizer.nextToken();
                                       bldgName=tokenizer.nextToken();
                                       postalCode=tokenizer.nextToken();
                                       totalIncome=Long.parseLong(tokenizer.nextToken());
                                       totalDonation=Long.parseLong(tokenizer.nextToken());
                                       totalPersonalRelief=Long.parseLong(tokenizer.nextToken());
                                       TaxPayerRecord person = new TaxPayerRecord(nric,name,dateOfBirth,gender,blockNo,unitNo,
                                                                                              streetName,bldgName,postalCode,totalIncome,
                                                                                              totalDonation,totalPersonalRelief);
                                       list.add(person);
                                       line=inFile1.readLine();
                                       }//end while
                              inFile1.close();
                             }// end try
                        catch (Exception e)
                              e.printStackTrace();
                        }//end catch
                        do{
                                  switch(choice)
                                       case 0:
                                       System.exit(0);
                                       break;
                                       case 1:
                                       // run list
                                       printList(list);
                                       break;
                                       case 2:
                                       printSummary(list);
                                       break;
                                       case 3:
                                       search(list,input);
                                       break;
                                  }//end switch
                             System.out.print(menu);
                             choice = input.nextInt();
                             System.out.println("");
                             }// end do
                             while(choice !=0);
                             Collections.sort(list);
         }//end TaxPayerProgramme()
         private void total(ArrayList<TaxPayerRecord> list)
              // Declaration
              double total=0;
              // calculate total
                   for (int i=0; i<list.size(); i++)
                   total=+ tax(i,list);
              //print msg
              System.out.println("Total revenue collectable for year 2006 (S$): "+total+"\n");
         private double tax(int i,ArrayList<TaxPayerRecord> list)
              // Declaration
              double income;
              double tax;
              // calculate income
              income =list.get(i).getTotalIncome()-list.get(i).getTotalDonation()
                        -list.get(i).getTotalPersonalRelief();
              // calculate tax
                   if (income>320000)
                        tax=(((income-320000)*0.21)+44850);
                   else if (income>160000)
                        tax=(((income-160000)*0.18)+16050);
                   else if (income>80000)
                        tax=(((income-80000)*0.145)+4450);
                   else if (income>40000)
                        tax=(((income-40000)*0.0875)+950);
                   else if (income>30000)
                        tax=(((income-30000)*0.0577)+375);
                   else
                        tax=((income-20000)*0.0577);
              return tax;
         private void totalAge(ArrayList<TaxPayerRecord> list)
                   // Declaration
                   String msg;
                   int i,age;
                   double grp1=0;
                   double grp2=0;
                   double grp3=0;
                   double grp4=0;
                   // calculate revenue by age
                        for (i=0; i<list.size(); i++)
                        age= 2006- Integer.parseInt(list.get(i).getDateOfBirth().substring(6,list.get(i).getDateOfBirth().length()));
                        if (age>55)
                             grp4 =+ tax(i,list);
                        else if (age>35)
                             grp3 =+ tax(i,list);
                        else if (age>17)
                             grp2 =+ tax(i,list);
                        else
                             grp1 =+ tax(i,list);
                   //print msg
                   msg="Total revenue by age range (S$) \n"+
                        "\t"+"(1 to 17)"+"\t"+ grp1 +"\n"     +
                        "\t"+"(18 to 35)"+"\t"+ grp2 +"\n"     +
                        "\t"+"(36 to 55)"+"\t"+ grp3 +"\n"     +
                        "\t"+"(above 55)"+"\t"+ grp4 +"\n";
                   System.out.println(msg);
        private void totalDistrict(ArrayList<TaxPayerRecord> list)
                   int count=1;
                   double temp=0;
                   double [][] array = new double [list.size()][2];
                        for (int i=0; i<list.size(); i++)
                        array[0]=Double.parseDouble(list.get(i).getPostalCode().substring(0,2));
                        array[i][1]=tax(i,list);
                   System.out.println("Total revenue by district (S$) ");
                        do{
                                  for (int a=0; a<list.size(); a++)
                                       if (count == array[a][0] )
                                       temp=array[a][1];
                                  }//end for loop
                             System.out.print("\t"+"(district "+count+")"+"\t"+ temp +"\n");
                             temp=0;
                             count++;
                        }while(count!= 80);// end of do_while loop
              System.out.print("\n");
         private void printList(ArrayList<TaxPayerRecord> list)
              System.out.println("List of Tax Payers fpr Year 2006");
                   for (int i=0; i<list.size(); i++)
                   System.out.println((i+1)+") "+list.get(i)+"|"+tax(i,list)+"\n");
         private void printSummary(ArrayList<TaxPayerRecord> list)
                   total(list);
                   totalAge(list);
                   totalDistrict(list);
         private void search(ArrayList<TaxPayerRecord> list,Scanner input)
                   int value;
                   System.out.print("Enter NRIC Number: ");
                   String nric = input.next();
                   Collections.sort(list);
                   value = Collections.binarySearch(list,nric);
         public static void main(String [] args)
                   new TaxPayerProgramme();
    Can someone help me with this?
    I can't find the error.
    The error msg display:
    C:\Documents and Settings\Xiong\Desktop\TaxPayerProgramme.java:285: cannot find symbol
    symbol : method binarySearch(java.util.ArrayList<TaxPayerRecord>,java.lang.String)
    location: class java.util.Collections
                   value = Collections.binarySearch(list,nric);
                   ^
    1 error
    Tool completed with exit code 1

    Well, this is the error, Java6 gives me on your code:The method binarySearch(List< ? extends Comparable<? super T> >, T) in the type Collections
    is not applicable for the arguments (ArrayList<TaxPayerRecord>, String)     The method expects the first parameter, to be a List whose children are Comparable to the second parameter. Your second parameter is String, so the List should be on String not on TaxPayerRecord, or, your second parameter should be a TaxPayerRecord and not a String.
    �dit: Another thought. From the error code you posted, I would assume, that you might have the wrong JDK libraries in your path.

  • Declaring an ArrayList

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

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

  • ArrayList() problems

    Hi!
    I need a little help getting an ArrayList to work. I am refactoring some of the classes in one of the O'Reilly books for a class assignment. I believe that I cannot get my ArrayList to add elements into itself. I'm not quite sure what I'm doing wrong. I'll post the code below. The problem arises in the last part of the code (at least I think it does) where i can't get my variable "size" (see the "for loop" below) to be resolved. I have tried initializing the variable at the beginning of the entire class in which case I can get the file to compile to a class. But when I run the class, I still get an ArrayOutOfBounds exception letting me know that my array is still initialized to 1 when i believe that and my index is a larger number (the number I input into the console). the message I get from the command line is:
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Error:
    java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:326)
    at MyFactorial.computeFactorialCacheB(MyFactorial.java:115) // this would be the second line of the "for" loop
    at MyFactorial.main(MyFactorial.java:134)
    Any help would be greatly appreciated. Thanks in advance.
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Here is my code
         public static synchronized BigInteger computeFactorialCacheB(String s) {
         private static int size;
    ArrayList table = new ArrayList();
              table.add(BigInteger.valueOf(1));
              int x = 0;
              try {
                   x = Integer.parseInt(s);
              catch (NumberFormatException e) {
                   System.out.println("the number you enter must be an integer");
              if (x<0) {
                   throw new IllegalArgumentException("x must not be a negative number");     
              else {
                   for(int size = table.size(); size <= x; size++);{
                        BigInteger lastfact = (BigInteger)table.get(size-1);
                        BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                        table.add(nextfact);
              return (BigInteger) table.get(size-1);
         }

    Thanks for your reply.
    As I said in my original posting, I am refactoring code from one of the O'Reilly books for an assignment. So no, this isn't all my code, just some of it (copyright is duly noted in my assignment).
    The semicolon was a great cach (thanks!) I truly didn't see it. The issue of the "size" variable is what I am trying to solve. When I originally entered the code int my IDE (eclipse) the first declaration of int size inside the for loop was OK but subsequent references to it (still in the for loop) wouldn't resolve.
         for(int size = table.size(); size <= x; size++){
               BigInteger lastfact = (BigInteger)table.get(size-1);
               BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                    table.add(nextfact);Hence the experimentation with the "size" variable. The use of the ArrayList was one of the parameters of the assignment. I see what you mean by creating a new list each time. The purpose of the method is to return a factorial (n!) using a BigInteger. This loop is pretty much just as it came out of O'rilley. It seems to work fine in their rendition (I guess that's why they get to write books).
    Tanks so much for your help. I'll refactor again and repost (probably tomorrow).
    � regards!

  • ArrayList and wrappers

    Can an ArrayList contain different types of objects from the same class?
    I know that it must be an object but can one be of type String and another be of type int?
    I am reading information from a file that looks something like this:
    Sam
    Jones
    21
    Tim
    Hendricks
    15
    I have written the following method:
    ArrayList list = new ArrayList();
    String fname;
    try
      BufferedReader br = new BufferedReader(new FileReader("student.txt"));
      while ((fname = br.readLine()) != null)
             String lname=br.readLine();
         int age= br.readLine();
         br.readLine(); //FOR THE BLANK LINE
         list.add(new Student(fname, lname, age));
      br.close();
    catch(IOException e)
      System.err.println(e.getMessage());
      System.exit(0);
    }If I declare age as type String the method and other methods work great, but I need to make it of type int.
    I have read up about wrappers and I think that is what I am suppose to use for the int but no matter what I do, I get tonnes of error messages.
    Any help would be appreciated.

    A better way would be to build a class for your data packet.
    class Thing {
      public final String name;
      public final int age;
      public Thing(String name, int age) {
        this.name = name;
        this.age = age;
    public class SomeClass {
      public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Thing("Jill",10));
        list.add(new Thing("John",20));
        list.add(new Thing("Janet",30));
        list.add(new Thing("Jeremy",40));
    }Then you can simply get your values back with
    for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {
      Thing thing = (Thing) iterator.next();
      System.out.println("Name: "+thing.name);
      System.out.println("Age: "+thing.age);
    }Or something like that...
    Talden

  • Reading into ArrayList problem - what is wrong?

    Hi, I am trying to read a list of strings into an ArrayList and am having some problems. I have created a main() which at the moment does nothing, its just to make sure that the array's content is genuine (meaning consistent with the string in the text file) so I am having it simply printed out to screen. The error I am getting is "cannot resolve symbol, variable array" by my compiler (Jcreator). I will paste the code below:
    import java.io.*;
    import java.util.*;
    public class hostList{
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
         new InputStreamReader(new FileInputStream(input)));
         ArrayList list=new ArrayList();
         String line;
         while((line=in.readLine())!=null)
              list.add(line);
         String[] array=new String[list.size()];
         list.toArray(array);
         in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
         public static void main (String [] args){
              System.out.println("Array content:");
              System.out.println("array " + array[0]);
              for (int i=0; array[i] !=null; i++)
                   System.out.println(array);
         }//main
    }//class
    Also, how would I use the array objects in another class, say class B. How can I access the arrays in class B so that i can use its methods? eg. array[i].doSomething(); where doSomething() is a method in class B. What libraries would i need to import (if any) ?
    Help is appreciated, thanks.

    this code wont compile bcas in main method u r not creating the object of this class also the var array is not globally declared hence wont be accesibile outside
    u can try this modified code
    import java.io.*;
    import java.util.*;
    public class hostList{
    String[] array=null;
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
    new InputStreamReader(new FileInputStream(input)));
    ArrayList list=new ArrayList();
    String line;
    while((line=in.readLine())!=null)
    list.add(line);
    array=new String[list.size()];
    list.toArray(array);
    in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
    public static void main (String [] args){
    hostList h=new hostList();
    System.out.println("Array content:");
    System.out.println("array " + h.array[0]);
    }//main
    }//class

  • Passing arraylist between constructors?

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

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

  • About ArrayList....

    Hi
    Hope you are fine.
    I have been stuck in a problem, can u plz help?
    Hoping for a quick response, thanks alot.
    Kind Regards,
    fastian
    code is here along with comments and problem descriptions.
    public boolean getProductList(ArrayList prodList)
    /* Caller has declared it as
    ArrayList tempList=new ArrayList();
    Assume we have 3 rows in DB as follows:
    ID     name     category     purchasePrice     salePrice     quantity     threshold     expiry
    1     milk     category 1     20     25     100     10     1/1/2007
    2     cream     cat2     0     0     0     0 10     1/1/2007
    3     sugar     cat3     0     0     0     0 10     1/1/2007
    Also Assume that the "Product" class has declared as follows:
    public String id;
    public String name;
    public String catagory;
    public int purchasePrice;
    public int salePrice;
    public int quantity;
    public int threshold;
    String sql = "SELECT * FROM product";
            cm = new connectionMngr();
            Product prod=new Product();
            Product prod1=new Product();
            System.out.println(sql);
            try
                rs = cm.executeQuery(sql);
                int i=0;
                while(rs.next())
                    prod.id= rs.getString("id");
                    prod.name= rs.getString("name");
                    prod.catagory= rs.getString("category");
                    prod.purchasePrice= rs.getInt("purchasePrice");
                    prod.salePrice= rs.getInt("salePrice");
                    prod.quantity= rs.getInt("quantity");
                    prod.threshold= rs.getInt("threshold");
                    if(prodList.add((Object)prod))
                        //System.out.println(prod.id + " in DL");
                    }/*Till this line the prodList contains valid rows*/
    System.out.println(((Product)prodList.get(i)).id+"--Varify");/*The line above, prints 1, 2 , and
    3 in three iterations*/
      i++;
                System.out.println("Prod successsfully added!!!!");
                cm.close();/*But here comes the source of problem, that is, all three lines print "3"
    which is assumed to be the output of 3rd line ONLY*/
                    System.out.println(((Product)prodList.get(0)).id+"--Varify22");
                    System.out.println(((Product)prodList.get(1)).id+"--Varify22");
                    System.out.println(((Product)prodList.get(2)).id+"--Varify22");
                return true;
            catch(Exception e)
                e.printStackTrace();
                System.out.println("Exception has been caught!!!!");
                cm.close();
                 return false;
        }

    Hi Dear,
    Please user the following code to solve your problem
    String sql = "SELECT * FROM product";
    cm = new connectionMngr();
    // Product prod=new Product(); //.........(1)
    Product prod1=new Product();
    System.out.println(sql);
    try
    rs = cm.executeQuery(sql);
    int i=0;
    while(rs.next())
    Product prod=new Product(); // ................(2)
    prod.id= rs.getString("id");
    prod.name= rs.getString("name");
    prod.catagory= rs.getString("category");
    prod.purchasePrice= rs.getInt("purchasePrice");
    prod.salePrice= rs.getInt("salePrice");
    prod.quantity= rs.getInt("quantity");
    prod.threshold= rs.getInt("threshold");
    if(prodList.add((Object)prod))
    //System.out.println(prod.id + " in DL");
    I have corrected the code as above .Please check at line mark as (1) and (2)
    thanks
    sushil

  • Displaying Arraylist in label

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

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

  • Generic arraylist

    hi, all. i am trying to implement my own queue which extends from the arraylist api and i am trying to use generic class. the problem is i have trouble using add method in the arraylist, when i did it. i got error says.
    Compiling 1 source file to H:\NetBean\UniqueQueueTest\build\classes
    H:\NetBean\UniqueQueueTest\src\uniquequeuetest\UniqueQueue.java:34: cannot find symbol
    symbol : method add(E)
    location: class uniquequeuetest.UniqueQueue<E>
    add(item);
    following is my part of the code.
    public class UniqueQueue<E extends Comparable<E> > extends ArrayList<E extends Comparable<E> >
    public UniqueQueue()
    super();
    public UniqueQueue(Collection<? extends E> c)
    super(c);
    public UniqueQueue(int initialCapacity)
    super(initialCapacity);
    public < E > boolean offer(E item)
    Comparable e;
    for(int i=0; i<size(); i++)
    e = (Comparable)get(i);
    if(((Comparable)item).compareTo(e) == 0)
    return false;
    this.add(item); <----this line causes error
    return true;
    thanks

    I think you should remove the <E> from the declaration of the 'offer' method. Written your way, it's a different 'E' from the one used in the class definition, so it's not compatible.
    Victor

Maybe you are looking for

  • Actionscript & changing form field values

    I am building a form using flash forms. I have a particular field that by default the value is 0.00. I want to make an onchange actionscript that will dynamically change the form field value to 0.00 if the end user deletes the value out of the field

  • [SOLVED] Pacman and ABS sync give different results

    I have been having a few issues with the NZ mirror, however they have been sorted. I have -Syy'ed a couple of times and get back: :: Starting full system upgrade... local database is up to date Which I know isn't the case as I visited the mirror via

  • Convert Teradata TIMESTAMP to SQL Server DateTime

    I have a Teradata TimeStamp(6) field which I have imported into a VarChar field in a staging table.  The values look like this: 1/22/2010 00:00:00.000000 9/15/2003 00:00:00.000000 10/10/2006 00:00:00.000000 I'm trying to move it to a permanent table

  • Clearing Online redo logs on the target physical standby

    Hi, Version 11202. Primary on machine A Standby on machine B Following note: 11.2 Data Guard Physical Standby Switchover Best Practices using SQL*Plus [ID 1304939.1]. Online redo logs on the target physical standby need to be cleared before that stan

  • Hide bounding box of a selected object

    I tried using the feature request page but got an error after typing all this and thankfully I copied all of the text I entered just before hitting submit just in case the website decided to act stupid like it did (would have to retype all of the fol