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

Similar Messages

  • Both of the advantages of ArrayList and LinkedList are needed.

    Hi there,
    I wonder how if I want performance on random access an ArrayList and also remove elements in any position of the List? As far as I know that a LinkedList is the best choice if I want to remove elements in any position of the List, but it's slow on traversing the List. Sometimes it's hard to choose between ArrayList and LinkedList, is there a way that I could have both advantages of ArrayList and LinkedList?
    Any suggestion?
    Thanks,
    Jax

    I think you might be interested in the data structure
    called a deque. It is built for fast insertions
    at both ends and is usually implemented as a linked
    list of arrays. The standard collections API does not
    offer this data structure (I wish it did). So you have
    to find a 3rd party implementation. Try searching
    Google: http://www.google.com/search?q=java+deque
    Thanks nasch and pervel for the information. What do you think if I do something like this?
    List a = new ArrayList();
    // perform some tasks that is fast with ArrayList
    List b = new LinkedList(a);
    // perform some tasks..
    Although a new object is created, but that perform better than one ArrayList or one LinkedList solely.

  • Arraylists and arrays

    i'm trying to put the numbers in an arraylist into an int[] array. could anyone tell me how this could be done? i tried the below but i get an error pointing to return divisors.toArray();
    import java.util.ArrayList;
    import java.util.List;
    class FactorsDemo {
        public static void main(String[] args) {
         //for(int i = 10; i < 30; i+=5) {
             int[] divisors = getDivisors(10);
        static int[] getDivisors(int n) {
         List<Integer> divisors = new ArrayList<Integer>();
         for(int d = 1; d <= n/2; d++) {
             if(n%d == 0) divisors.add(new Integer(d));
         return divisors.toArray();
    }

    i'm trying to get this code to compile without using generics, just to see how it is done. it gets the divisors of a number, puts them into an arraylist, and then returns an array with those same divisors.
    i tried to cast the arraylist object to an int, but it's not working.
    can anyone show me what i need to do?
    import java.util.ArrayList;
    import java.util.List;
    class FactorsDemo2 {
        public static void main(String[] args) {
         for(int i = 10; i < 50; i+=5) {
             System.out.print("Factors of "+i+": ");
             int[] divisors = getDivisors(i);
             display(divisors);
        static int[] getDivisors(int n) {
         List divisors = new ArrayList();
         for(int d = 1; d <= n/2; d++) {
             if(n%d == 0) divisors.add(new Integer(d));
         int[] myInts = new int[divisors.size()];
            for(int i = 0; i < divisors.size(); i++) {
                   myInts[i] = (int) divisors.get(i);
            return myInts;
        static void display(int[] x) {
         for(int i = 0; i < x.length; i++) {
             System.out.print(x[i]+" ");
         System.out.println();
    }FactorsDemo2.java:21: inconvertible types
    found : java.lang.Object
    required: int
    myInts[i] = (int) divisors.get(i);
    ^
    Note: FactorsDemo2.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error

  • Differece between ArrayList and LinkedList

    Differece between ArrayList and LinkedList

    An array list is implemented as an array. A LinkedList is implemented as a series of separate nodes linked by references.
    Although they both support the same methods, that has performance implications. Linked lists are better at inserting and deleting arbitary elements, but are slow to reference an element by index.

  • ArrayList and double[]

    private double[] findAverageFace(ResultSet rs, int rows){
            String path;
            Scanner scanner;
            int picn = 0;
            double[] avgFace = new double[rows * rows];
            try{
                //System.out.println("scanning the result set");
                double[] pic;
                while(rs.next()){
                    path = rs.getString(1); //the path to the matrix
                    //System.out.println("path: " +path);
                    scanner = new Scanner (new File(path));
                    pic = new double[rows * rows];
                    for(int i=0; i<rows*rows; i++){
                        pic[i] = scanner.nextFloat();
                        avgFace[i] += pic;
    //lets add a clone of the pic array
    // k++;
    //System.out.println("\tmatrix: " + k);
    //matricesToolbox.MatrixToolbox.printMatrix(avgFace);
    facesArrayList.add(pic.clone());
    picn++;
    //System.out.println("pic n : "+ picn);
    for(int i=0; i<rows*rows; i++)
    avgFace[i] /= picn;
    return(avgFace);
    }catch(Exception e){
    e.printStackTrace();
    return(null);
    private ArrayList calculateDifferenceFaces(double[] avgFace){
    ArrayList xArrayList = new ArrayList();
    double[] pic;
    double[] phi = new double[avgFace.length];
    for(int i=0; i< facesArrayList.size(); i++){
    pic = (double[]) facesArrayList.get(i);
    for(int j=0; j< pic.length*pic.length; j++){
    System.out.println(pic[j] + " minus " + avgFace[j]);
    //System.out.println(avgFace[j] + "");
    phi[j] = pic[j] - avgFace[j];
    //System.out.print(phi[j] + " ");
    xArrayList.add(phi);
    return(xArrayList);
    }why in line "System.out.println(pic[j] + " minus " + avgFace[j]);" i get the same values for both pic and avgFace, although in the 1st method i add a clone of pic  facesArrayList.add(pic.clone()); ??                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I would suggest;
    - using a debugger. This will show if the arrays are the same or not. avgFace will be the same each time for each pics as its the same array.
    - use nextDouble() as nextFloat() is less accurate (I am guessing not a problem here)]
    - don't use pic.clone(), just create a new array at the start of each loop.

  • Comparing Arraylist and String

    Plz can anyone help me to find that this what will be the behaviour of this code.I have an Enumeration and and ArrayList.I want to comapre each object of Enumeration with each object of ArrayList.The code is
    private boolean checkDeviceType(HttpServletRequest request){
              Enumeration e = request.getHeaderNames();
              String tmp = null;
              //String[] strKeys = null;
              ArrayList al = getValues("test");
              while(e.hasMoreElements()){
                   tmp = (String)e.nextElement();
                   for(int i = 0; i < al.size(); i++){
                        if(tmp.equalsIgnoreCase(al.toString()))// Ye line theek se check kar ki chalegi ya nahin
                   return true;
              return false;
         }

    Plz can anyone help me to find that this what will be
    the behaviour of this code.I have an Enumeration and
    and ArrayList.I want to comapre each object of
    Enumeration with each object of ArrayList.The code
    is
    > private boolean checkDeviceType(HttpServletRequest
    request){
              Enumeration e = request.getHeaderNames();
              String tmp = null;
              //String[] strKeys = null;
              ArrayList al = getValues("test");
              while(e.hasMoreElements()){
                   tmp = (String)e.nextElement();
                   for(int i = 0; i < al.size(); i++){
    if(tmp.equalsIgnoreCase(al.get(i).toString()))// Ye line line theek se check kar ki chalegi ya nahin
                   return true;
              return false;
         }You didn't extract the object from the ArrayList--so, your toString converts the whole ArrayList to a String, not just a single element. I fixed the line with your comment--added "get(i)."
    Please use code tags (button above posting box) when posting code.

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Retrieving data from an ArrayList and presenting them in a JSP

    Dear Fellow Java Developers:
    I am developing a catalogue site that would give the user the option of viewing items on a JSP page. The thing is, a user may request to view a certain item of which there are several varieties, for example "shirts". There may be 20 different varieties, and the catalogue page would present the 20 different shirts on the page. However, I want to give the user the option of either viewing all the shirts on a single page, or view a certain number at a time, and view the other shirts on a second or third JSP page.
    See the following link as an example:
    http://www.eddiebauer.com/eb/cat_default.asp?nv=2|21472|9&tid=&c=&sc=&cm_cg=&lp=n2f
    I am able to retrieve the data from the database, and present all of them on a JSP, however I am not sure how to implement the functionality so that they can be viewed a certain number at a time. So if I want to present say 12 items on a page and the database resultset brings back 30 items, I should be able to present the first 12 items on page1, the next 12 items on page2, and the remaining 6 items on page3. How would I do this? Below is my scriplet code that I use to retrieve information from the ArrayList that I retrieve from my database and present them in their entirety on a single JSP page:
    <table>
    <tr>
    <%String product=request.getParameter("item");
    ArrayList list=aBean.getCatalogueData(product);
    int j=0, n=2;
    for(Iterator i=list.iterator(); i.hasNext(); j++){
    if(j>n){
    out.print("</tr><tr>");
    j=0;
    Integer id=(Integer)i.next();
    String name=(String)i.next();
    String productURL=(String)i.next();
    out.print("a bunch of html with the above variables embedded inside")
    %>
    </tr>
    </table>
    where aBean is an instace of a JavaBean that retrieves the data from the Database.
    I have two ideas, because each iteration of the for loop represents one row from the database, I was thinking of introducing another int variable k that would be used to count all the iterations in the for loop, thus knowing the exact number. Once we had that value, we would then be able to determine if it was greater than or less than or equal to the maximum number of items we wanted to present on the JSP page( in this case 12). Once we had that value would then pass that value along to the next page and the for loop in each subsequent JSP page would continue from where the previous JSP page left off. The other option, would be to create a new ArrayList for each JSP page, where each JSP page would have an ArrayList that held all the items that it would present and that was it. Which approach is best? And more importantly, how would I implement it?
    Just wondering.
    Thanks in advance to all that reply.
    Sincerely;
    Fayyaz

    -You said to pass two parameters in the request,
    "start", and "count". The initial values for "start"
    would be zero, and the inital value for "count" would
    be the number of rows in the resultSet from the
    database, correct?Correct.
    -I am a little fuzzy about the following block of code
    you gave:
    //Set start and count for next page
    start += count; // If less than count left in array, send the number left to next next page
    count = ((start*3)+(count*3) < list.size()) ? (count) : ((list.size() - (start*3))/3)
    Could you explain the above block of code a little
    further please?Okay, first, I was using the ternary operators (boolean) ? val_if_true : val_if_false;
    This works like an if() else ; statement, where the expression before the ? represents the condition of the if statement, the result of the expression directly after the ? is returned if the condition is true, and the expression after the : is returned if the condition is false. These two statments below, one using the ternary ? : operators, and the other an if/else, do the same thing:
    count = ((start*3)+(count*3) < list.size()) ? (count) : ((list.size() - (start*3))/3);
    if ((start*3)+(count*3) < list.size()) count = count;
    else count = ((list.size() - (start*3))/3);Now, why all the multiplying by 3s? Because you store three values in your list for each product, 1) the product ID, 2) the product Name, and 3) the product URL. So to look at the third item, we need to be looking at the 9th,10th, and 11th values in the list.
    So I want to avoid an ArrayIndexOutOfBounds error from occuring if I try to access the List by an index greater than the size of the list. Since I am working with product numbers, and not the number of items stored in the list, I need to multiply by three, both the start and count, to make sure their sum does not exceed the value stored in the list. I test this with ((start*3)+(count*3) < list.size()) ?. It could have been done like: ((start + count) * 3 < list.size()) ?.
    So if this is true, the next page can begin looking through the list at the correct start position and find the number of items we want to display without overstepping the end of the list. So we can leave count the way it is.
    If this is false, then we want to change count so we will only traverse the number of products that are left in the list. To do this, we subtract where the next page is going to start looking in the list (start*3) from the total size of the list, and devide that by 3, to get the number of products left (which will be less then count. To do this, I used: ((list.size() - (start*3))/3), but I could have used: ((list.size()/3) - start).
    Does this explain it enough? I don't think I used the best math in the original post, and the line might be better written as:
    count = ((size + count)*3 < list.size()) ? (count) : ((list.size()/3) - start);All this math would be unnecessary if you made a ProductBean that stored the three values in it.
    >
    - You have the following code snippet:
    //Get the string to display this same JSP, but with new start and count
    String nextDisplayURL = encodeRedirectURL("thispage.jsp?start=" + start + "&count=" + count + "&item=" + product);
    %>
    <a href="<%=nextDisplayURL%>">Next Page</a>
    How would you do a previous page URL? Also, I need to
    place the "previous", "next" and the different page
    number values at the top of the JSP page, as in the
    following url:
    http://www.eddiebauer.com/eb/cat_default.asp?nv=2|21472
    9&tid=&c=&sc=&cm_cg=&lp=n2f
    How do I do this? I figure this might be a problem
    since I am processing the code in the middle of the
    page, and then I need to have these variables right at
    the top. Any suggestions?One way is to make new variable names, 'nextStart', 'previousStart', 'nextCount', 'previousCount'.
    Calculate these at the top, based on start and count, but leave the ints you use for start and count unchanged. You may want to store the count in the session rather than pass it along, if this is the case. Then you just worry about the start, or page number (start would be (page number - 1) * count. This would be better because the count for the last page will be less than the count on other pages, If we put the count in session we will remember that for previous pages...
    I think with the details I provided in this and previous post, you should be able to write the necessary code.
    >
    Thanks once again for all of your help, I really do
    appreciate the time and effort.
    Take care.
    Sincerely;
    Fayyaz

  • How to keep value in arrayList and print into matrix form.

    compute all primes less than N, and display the results
    step by step .summarize the computed results in an easy-to-read format.(matrix)
    The program starts by asking for an integer value N from the user. Print out the initial matrix
    of numbers from 2 to N.
    To find all primes less than N, begin by making a table of integers from 2 to N.
    Find the smallest integer i, that is NOT prime and NOT crossed out. Mark i as a prime
    number and cross out 2i, 3i, 4i, ?, ni N.
    At this point, program should print the intermediate results in a matrix format, and pause
    until any key is pressed before proceeding.clear screen every
    time prior to printing the intermediate results (in the matrix format).
    When i > N , the algorithm terminates. screen is cleared once again,
    before the program prints the final results in the matrix format.
    Following are the requirements for the matrix format:
    - The matrix consists of 10 columns
    - The number of rows varies, depending on the input N
    - Initial matrix: The program prints an empty string in place of 1
    - Intermediate matrix: The program prints values for all prime numbers and numbers
    that are not crossed out. The program prints an empty string for each crossed-out
    number.
    Final matrix: The program prints only the prime numbers less than N
    P.S I want to write at least 3 classes

    This is my new first class but it have an error
    import java.io.*;
    import java.util.*;
    public class ArrayListExample2 {
        public static void main(String[] args)throws IOException {
            ArrayListExample listExample = new ArrayListExample();
            listExample.doArrayListExample();
        public void doArrayListExample()throws IOException {
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             System.out.print("enter limit : ");
              int max=Integer.parseInt(br.readLine());
              System.out.println();
            int counter = 2;
            List listA = new ArrayList();// int list
            //List listB = new ArrayList(); //string list
            for (int i = 2; i <= max; i++) {
                System.out.print("\t" + i );
                listA.add(new Integer(i)); //???????2-max ??listA
              int count =0;
              BufferedReader en = new BufferedReader(new InputStreamReader(System.in));
              while(count<Math.sqrt(max))
                     // max may be number of input or size of array list
              //BufferedReader en = new BufferedReader(new InputStreamReader(System.in));
              System.out.println ("Please enter");
              en.readLine();// wait for enter
              listA.removeNotPrime();
              count++;
         public void removeNotPrime()// what parametor?Need?
              for (int i=0;i<Math.sqrt(max)))
                   int prime = listA.get(i);
                        for (int j=i+1;i<=listA.size();j++)
                         int val = listA.get(j);
                        if (val%prime==0)
                        listA.remove(j);
    This part for test
            for (int i = 0; i <= max; i++)  // printttttttttt
                //System.out.print("\t" + i );
                   System.out.print("\t" + listA.get(i);
                // call class printMatrix;
    }

  • Design choice between ArrayList and LinkedList

    Can someone clarify me which is better suited (efficient) for use?
    It appears to me that both can be used very much interchangeably at least from functionality point of view. :(

    Using the following code (and I'm sure someone will come nitpicking about it) I get the (expected, at least by me from prior experience) result that iteration over a LinkedList is about twice as fast as iteration over an ArrayList, but lookup operations on an ArrayList are substantially faster:
    package jtw.test;
    import java.util.*;
    public class SpeedTest {
        public static void main(String... args) throws Exception {
            List<Integer> linked = new LinkedList<Integer>();
            List<Integer> arr = new ArrayList<Integer>();
            for (int i = 0; i < 1e3; i++) {
                linked.add(i);
                arr.add(i);
            long r = 0;
            Date startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: linked) {
                     r += q;
            Date stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            Date startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (Integer q: arr) {
                     r += q;
            Date stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList iteration: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList iteration: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
             r = 0;
            startLinked = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += linked.get(j);
            stopLinked = new Date();
            System.out.println("Total: " + r);
            r = 0;
            startArr = new Date();
            for (int i = 0; i < 1e3; i++) {
                for (int j = 999; j >= 0; j--) {
                     r += arr.get(j);
            stopArr = new Date();
            System.out.println("Total: " + r);
            System.out.println("LinkedList lookup: " + startLinked + " to " + stopLinked + " took " + (stopLinked.getTime() - startLinked.getTime()));
            System.out.println(" ArrayList lookup: " + startArr + " to " + stopArr + " took " + (stopArr.getTime() - startArr.getTime()));
    }Gets the result:
    D:\jdk1.6.0_05\bin\java -Didea.launcher.port=7540 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\bin" -Dfile.encoding=windows-1252 -classpath "D:\jdk1.6.0_05\jre\lib\charsets.jar;D:\jdk1.6.0_05\jre\lib\deploy.jar;D:\jdk1.6.0_05\jre\lib\javaws.jar;D:\jdk1.6.0_05\jre\lib\jce.jar;D:\jdk1.6.0_05\jre\lib\jsse.jar;D:\jdk1.6.0_05\jre\lib\management-agent.jar;D:\jdk1.6.0_05\jre\lib\plugin.jar;D:\jdk1.6.0_05\jre\lib\resources.jar;D:\jdk1.6.0_05\jre\lib\rt.jar;D:\jdk1.6.0_05\jre\lib\ext\dnsns.jar;D:\jdk1.6.0_05\jre\lib\ext\localedata.jar;D:\jdk1.6.0_05\jre\lib\ext\sunjce_provider.jar;D:\jdk1.6.0_05\jre\lib\ext\sunmscapi.jar;D:\jdk1.6.0_05\jre\lib\ext\sunpkcs11.jar;F:\dev\Euler\out\production\Euler;C:\Program Files\JetBrains\IntelliJ IDEA 8.0.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain jtw.test.SpeedTest
    Total: 499500000
    Total: 499500000
    LinkedList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 30
    ArrayList iteration: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:41 CET 2009 took 53
    Total: 499500000
    Total: 499500000
    LinkedList lookup: Wed Jan 21 07:32:41 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 424
    ArrayList lookup: Wed Jan 21 07:32:42 CET 2009 to Wed Jan 21 07:32:42 CET 2009 took 22
    Process finished with exit code 0Given the internal representation of the datatypes, this is to be expected.

  • Working with ArrayList and classes

    Hi:
    I'm trying to create a program that adds and remove information to an ArrayList. I can't figure out the errors that I'm having. See if anyone can help me.
    import javax.swing.JOptionPane;
    import java.io.*;
    import java.util.*;
    public class StudentRegistration {
        class Name
           // String first = JOptionPane.showInputDialog(null,"Enter First Name","First Name", JOptionPane.QUESTION_MESSAGE);
           // String last = JOptionPane.showInputDialog(null,"Enter Last Name","Last Name", JOptionPane.QUESTION_MESSAGE);
            String first, last;
            Name(String first, String last)
                this.first = first;
                this.last =last;                   
            String getFirstName()
                return first;           
            String getLastName()
                return last;
        class Address
            String street, city, state, zipcode;
            Address(String street, String city, String state, String zipcode)
                this.street = street;
                this.city = city;
                this.state = state;
                this.zipcode = zipcode;
            String getStreet()
                return street;
            String getCity()
                return city;
            String getState()
                return state;
            String getZipCode()
                return zipcode;
         public class Student
            String id;
            Date date;
            Address address;
            Name name;
            Student (String id, Name name, Address address)
                this.id = id;
                this.name =name;
                this.address = address;
                date = new Date();
            String getId()
                return id;
        class Admissions
            ArrayList list;
            int i;
            boolean found;
            Admissions()
                list = new ArrayList();
            void addStudent(Student s)
                list.add(s);
            Object getStudent(int i)
                return list.remove(i);
            boolean Empty()
                return list.isEmpty();
            boolean getIndex(String id)
                int i, index;
                boolean found;
                while(i < index && !found)
                    Object o = list.get(i);
                    if (o instanceof Student)
                        Student s = (Student) o;
                        if (s.getId().compareto(id))
                            found = true;
                        else i++ ;
               return found;
        public static void main(String[] args)
            Admissions adm = new Admissions();
            Admissions drop = new Admissions();
            boolean cont;
            while(cont = true)
                  String input = JOptionPane.showInputDialog(null, "Enter Selection Number:\n\n 1 - Add Student\n 2 - Remove Student\n 3 - Print List\n 4 - Quit\n" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                  int selection = Integer.parseInt(input);
                    switch (selection)
                    case 1:{
                        String first = JOptionPane.showInputDialog(null, "First Name:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String last = JOptionPane.showInputDialog(null, "Last Name:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Name name = new Name(first, last);
                        String street = JOptionPane.showInputDialog(null, "Street Address:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String city = JOptionPane.showInputDialog(null, "City:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String state = JOptionPane.showInputDialog(null, "State:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String zipcode = JOptionPane.showInputDialog(null, "Zip Code:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Address address = new Address(street, city, state, zipcode);
                        String id = JOptionPane.showInputDialog(null, "Student ID:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Student s = new Student(name, address, id);
                        adm.addToList(s);
                    case 2:{
                        if(!adm.Empty());
                            String id = JOptionPane.showInputDialog(null, "Student ID:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                            if(adm.getIndex(id))
                                index = adm.index();
                                drop.addToList(adm.getStudent(index));
                    case 3:{
               case 4: break;
               default: JOptionPane.showMessageDialog(null,"Wrong selection.");
            System.exit(0);
        

    yes i did but it didn't changed anything..... but I fixed them by making the classes static. Logically is ok but I 'm not sure really if it 's ok. Now I have only one error two times here is the code again and the output...
    import javax.swing.JOptionPane;
    import java.io.*;
    import java.util.*;
    public class StudentRegistration {
        public static class Name
            String first, last;
            Name(String first, String last)
                this.first = first;
                this.last =last;                   
            String getFirstName()
                return first;           
            String getLastName()
                return last;
        public static class Address
            String street, city, state, zipcode;
            Address(String street, String city, String state, String zipcode)
                this.street = street;
                this.city = city;
                this.state = state;
                this.zipcode = zipcode;
            String getStreet()
                return street;
            String getCity()
                return city;
            String getState()
                return state;
            String getZipCode()
                return zipcode;
         public static class Student
            String id;
            Date date;
            Address address;
            Name name;
            Student (String id, Name name, Address address)
                this.id = id;
                this.name =name;
                this.address = address;
                date = new Date();
            String getId()
                return id;
        public static class Admissions
            ArrayList list;
            int i, index, lastindex = list.size();
            boolean found;
            Admissions()
                list = new ArrayList();
            void addStudent(Student s)
                list.add(s);
            Object getStudent(int i)
                return list.remove(i);
            boolean Empty()
                return list.isEmpty();
            boolean getFound(String id)
                while(i < lastindex && !found)
                    Object o = list.get(i);
                    if (o instanceof Student)
                        Student s = (Student) o;
                        if (s.getId().compareTo(id) == 0)
                            found = true;
                        else i++ ;
               return found;
            int getIndex(String id)
                while(i < lastindex && !found)
                   Object index = list.get(i);
                    if (index instanceof Student)
                        Student s = (Student) index;
                        if (s.getId().compareTo(id) == 0)
                            found = true;
                        else i++ ;
                 return index;          
        public static void main(String[] args)
            Admissions adm = new Admissions();
            Admissions drop = new Admissions();
            boolean cont;
            while(cont = true)
                  String input = JOptionPane.showInputDialog(null, "Enter Selection Number:\n\n 1 - Add Student\n 2 - Remove Student\n 3 - Print List\n 4 - Quit\n" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                  int selection = Integer.parseInt(input);
                    switch (selection)
                    case 1:{
                        String first = JOptionPane.showInputDialog(null, "First Name:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String last = JOptionPane.showInputDialog(null, "Last Name:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Name name = new Name(first, last);
                        String street = JOptionPane.showInputDialog(null, "Street Address:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String city = JOptionPane.showInputDialog(null, "City:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String state = JOptionPane.showInputDialog(null, "State:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        String zipcode = JOptionPane.showInputDialog(null, "Zip Code:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Address address = new Address(street, city, state, zipcode);
                        String id = JOptionPane.showInputDialog(null, "Student ID:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                        Student s = new Student(id, name, address);
                        adm.addToList(s);     //The error is here. It says that can't find add.ToList
                    case 2:{
                        if(!adm.Empty());
                            String id = JOptionPane.showInputDialog(null, "Student ID:" ,"Sutdents Services", JOptionPane.QUESTION_MESSAGE);
                            if(adm.getFound(id))
                               int index = adm.getIndex(id);
                               drop.addTolist(adm.getStudent(index));  //And also here. Same error
                    case 3:{
               case 4: break;
               default: JOptionPane.showMessageDialog(null,"Wrong selection.");
            System.exit(0);
    }This is in the output window:
    init:
    deps-jar:
    Compiling 1 source file to C:\Java\StudentRegistration\build\classes
    C:\Java\StudentRegistration\src\StudentRegistration.java:184: cannot find symbol
    symbol : method addTolist(StudentRegistration.Student)
    location: class StudentRegistration.Admissions
    adm.addTolist(s);
    C:\Java\StudentRegistration\src\StudentRegistration.java:195: cannot find symbol
    symbol : method addTolist(java.lang.Object)
    location: class StudentRegistration.Admissions
    drop.addTolist(adm.getStudent(index));
    Note: C:\Java\StudentRegistration\src\StudentRegistration.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    2 errors
    BUILD FAILED (total time: 0 seconds)

  • Rendering Images from a s:Arraylist and datagroup

    Ok, I have one last problem that is perplexing me.  I am seeing the following when I run my application:
    In my code I have main.mxml:
    <fx:Declarations>
              <!--<mx:HTTPService id="mediaData" url="http://www.serco-hrc.com/SNAmedia/pictures.xml" />-->
              <s:ArrayList id="tempData">
                   <fx:String>1 Picture</fx:String>
                   <s:BitmapImage source="SNA_media/pictures/1.jpg"/>
                   <fx:String>2 Picture</fx:String>
                   <s:BitmapImage source="SNA_media/pictures/2.jpg"/>
                   <fx:String>3 Picture</fx:String>
                   <s:BitmapImage source="SNA_media/pictures/3.jpg"/>
                   <fx:String>4 Picture</fx:String>
                   <s:BitmapImage source="SNA_media/pictures/4.jpg"/>
              </s:ArrayList>
         </fx:Declarations>
         <s:HGroup left="10" top="78" width="100%">
              <s:Panel id="thumbsPanel" title="Thumbnails">
                   <s:DataGroup id="mediaGroup" dataProvider="{tempData}" itemRenderer="components.NameDisplay">
                        <s:layout>
                             <s:VerticalLayout useVirtualLayout="true" />
                        </s:layout>
                   </s:DataGroup>
                   <s:VScrollBar right="0" height="100%" viewport="{mediaGroup}"/>
              </s:Panel>
              </s:HGroup>
    There are other panels within my HGroup that have been commented out and have nothing to do with my issue here.  In my components.NameDisplay:
    <s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                        xmlns:s="library://ns.adobe.com/flex/spark"
                        xmlns:mx="library://ns.adobe.com/flex/mx"
                        autoDrawBackground="true">
         <fx:Script>
              <![CDATA[
                   import spark.skins.spark.DefaultComplexItemRenderer;
                   import spark.skins.spark.DefaultItemRenderer;
                   private function rendererFunction(item:Object):ClassFactory {
                        if (item is String) {
                             return new ClassFactory(NameDisplay);
                        } else {
                             return new ClassFactory(DefaultComplexItemRenderer);
              ]]>
         </fx:Script>
         <s:states>
              <s:State name="normal"/>
              <s:State name="hovered"/>
         </s:states>
         <s:Image width="100" height="100"
                    source="{data.source}"
                    horizontalAlign="center" verticalAlign="middle"></s:Image>
         <s:Label text="{data}"
                    height="30" width="40"
                    color="black" textAlign="center"
                    verticalAlign="middle"></s:Label>
    </s:ItemRenderer>
    My images are coming from a Linked folder within my project as in:
    After all this, I thought I did everything correctly.  Why are my images not showing up when I run my application?????
    Tony

    I finally figured out that I will have to absolute address my images within my s:ArrayList.  I thought I could use a project "linked folder" as a go-between, but that schema is not working as I envisioned. So my arraylist now looks like:
    <s:ArrayList id="tempData">
                   <fx:String>1 Picture</fx:String>
                   <s:BitmapImage source="I:\Documents\development\SERCO\SNA_media\pictures\1.jpg"/>
                   <fx:String>2 Picture</fx:String>
                   <s:BitmapImage source="I:\Documents\development\SERCO\SNA_media\pictures\2.jpg"/>
                   <fx:String>3 Picture</fx:String>
                   <s:BitmapImage source="I:\Documents\development\SERCO\SNA_media\pictures\3.jpg"/>
                   <fx:String>4 Picture</fx:String>
                   <s:BitmapImage source="I:\Documents\development\SERCO\SNA_media\pictures\4.jpg"/>
    Atleast my images are now displaying in the panel. Now if I could figure out why that "[Object Bitmap" text is showing up over the top of my images.
    Any suggestions???  I have not changed anything in my code, yet.
    Tony

  • JAX-RPC ArrayLists and Jave Beans

    Can any one tell me if JAX-RPC supports an ArrayList of JavaBeans

    In my experience, Apache Axis is capable of serializing and deserializing any java.util.Collection instance, provided it can serialize and deserialize the objects held by the collection. This means that a List populated with beans should cause no problems.
    A word of caution though: XML serialization of objects is nowhere near as fast as the 'usual' Java serialization. This means that -if you're sending or receiving large amounts of beans per call- you might consider sending and receiving the List as attachment (ie: binary). I realize this defeats interoperability for the related web service methods, but having your users wait dozens of seconds on responses is rarely a viable alternative.

  • ArrayLists and Java 6.0

    Nevermind, I figured it out.
    Message was edited by:
    dayrinni

    I must agree. When I compile using command line there
    is no error. But for some odd reason Eclipse is
    giving me an error telling me I am not able to do
    something like
    ArrayList<MyObject> list = new
    ArrayList<MyObject>();
    Is anyone else getting errors like this with their
    compilers and editors?change the compiler compliance settings:
    Windows->Preferences->Java->Compiler->Compiler COmpliance Level needs to be 5.0 or greater. if you don't have the option of going higher than 1.4, you need a newer eclipse. you really do. it won't matter a single bit that you have the latest JDK installed, Eclipse doesn't use that. you need eclipse 3.1 or later
    (unless you want to go mucking about with external builders, but trust me, you don't)

  • ArrayLists and webservers

    Hi,
    I wonder if anyone can help. I have a method in a class contained in a WebServer called addItem. I also have a client class that calls the drives the web server. The problem is that when i try and add an item it doesn't appear to add the item to and arraylist that i've set up. Im not quite sure why it doesn't do this. Hopefully someone can help. Cheers.
    gillersuk
    ArrayList items = new ArrayList();
    HashMap stock = new HashMap();
    HashMap shoppingbaskets = new HashMap();
    String shop = "shop";
    public static String t;
    public boolean addItems(java.lang.String itemID, java.lang.String token, int number, double price) throws java.rmi.RemoteException {
    AuthServiceLocator locator = new AuthServiceLocator();
    try {
    Auth stub = locator.getAuth();
    if(stub.check(token,true)){
    Item a = new Item();
    a.setItemID(itemID);
    a.setPrice(price);
    items.add(a);
    if(!(stock.containsKey(itemID))){
    Integer i = new Integer(number);
    stock.put(itemID,i);
    return true;
    else {
    Integer i = new Integer(((Integer) stock.get(itemID)).intValue());
    int j = i.intValue();
    j += number;
    Integer k = new Integer(j);
    stock.put(itemID,k);
    return true;
    return false;
    }catch (ServiceException e){
    return false;
    CLIENT CODE
    System.out.println("Please enter the itemID, the number of items and the price of the item seperated by the # symbol");
    final String tLine = tKeyboard.readLine();
    final StringTokenizer tTokens = new StringTokenizer(tLine, "#");
    String newItemID = tTokens.nextToken();
    int number = Integer.parseInt(tTokens.nextToken());
    double price = Double.parseDouble(tTokens.nextToken());
    boolean bool = shopCall.addItems(newItemID, token, number, price);
    System.out.println(bool);
    if(bool){
    System.out.println(shopCall.viewItem(newItemID));
    }

    Hi,
    cann u clarify a few doubts that I have ?
    1) What is the class that ur talking about ? is it an EJB bean or a concrete normal java class?
    2) The code says that the arraylist is a instance level variable and hence i doubt whther ur checking the content of the arraylist in the correct Object or not...I meant to aay u that plz ensure that ur verifying the contents of the arraylist on the same object in which u have inserted the item.
    3) The client side code is perfect ,but just confirm that ur server side object that it refers in both the cases in the same one or not
    When ever

Maybe you are looking for

  • How To Display Image Dimension in Pixels Rather Than Inches

    I am using Photoshop CS3, which I'm still learning to use.  I want to see an open image's dimension (W X H) in pixels in the image's window/workspace. Right now, when I open a file it displays the file's Document Sizes in the lower part of the worksp

  • Color correcting FOOD photos

    I need to color correct gourmet food photos for large format printing on a company truck. Any tips or suggestions on books or links to guide me. Thanks.

  • After Repairing Permissions, "Warning: SUID file. . ."  So, is it a concern

    Warning: SUID file "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAg ent" has been modified and will not be repaired. I don't what this means, nor even where to begin to find out. Thoughts.

  • Forum / wiki... trying to better understand

    So I have been around here almost a year and this is my first forum I have been consistently active on.  There are some things I don't understand I would like to clear up. 1) forum titles (ranks?) admin moderator make sense but things like trusted us

  • RAC OCCI connectString

    Dear all, Recently i have set up a 2-node RAC environment, and i will put the my application on the local host. The rac database global name: agdb.world, the 2 instances respectively are agdb1 and agdb2. i also use the DBCA to create a service name a