Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Can someone show me how to add an integer to a list please? (http://www.go4expert.com/forums/add-integer-list-t27379/)

George91340 15Dec2011 11:00

Can someone show me how to add an integer to a list please?
 
Here is my code so far. The bolded code is giving me errors. Thanks in advance for your help! =D

Code:

public class ListTest
{
  public static void main( String args[] )
  {
      List list = new List();
      // create the List container
      // insert integers in list
    //  add code here to insert the following values
    // at the back of the list ( -1  0  1  5  )
   
 
      list.add(-1); // add code here
      list.print();
      list.add(0); // add code here
      list.print();
    list.add(1); //  add code here
      list.print();
    list.add(5); //  add code here
      list.print();
      // remove objects from list; print after each removal
      try
      {
        Object removedObject = list.removeFromFront();
        System.out.printf( "%s removed\n", removedObject );
        list.print();
        removedObject = list.removeFromFront();
        System.out.printf( "%s removed\n", removedObject );
        list.print();
        removedObject = list.removeFromBack();
        System.out.printf( "%s removed\n", removedObject );
        list.print();
        removedObject = list.removeFromBack();
        System.out.printf( "%s removed\n", removedObject );
        list.print();
      } // end try
      catch ( EmptyListException emptyListException )
      {
        emptyListException.printStackTrace();
      } // end catch
  } // end main
} // end class ListTest


ewaldhorn 28Dec2011 13:40

Re: Can someone show me how to add an integer to a list please?
 
Hi.

Lists store OBJECTS, not primitives. You have a few choices here, you could either convert the List to an Array, which then removes the automatic growth management, or, you could store the numbers as Integers, which are actual objects. For example:

Code:

Integer number = new Integer(-5);
list.add(number);

That way, you should be able to use a List to store values. It's not the most efficient way to do it, because of all the objects, but if it's a small application with not a lot of concurrent users, that's fine.

I hope this helps.


All times are GMT +5.5. The time now is 06:54.