Can someone show me how to add an integer to a list please?

Discussion in 'Java' started by George91340, Dec 15, 2011.

  1. George91340

    George91340 New Member

    Joined:
    Dec 15, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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  )
        
     
          [B]list.add(-1);[/B] // add code here
          list.print();
          [B]list.add(0);[/B] // add code here
          list.print();
         [B] list.add(1);[/B] //  add code here
          list.print();
         [B] list.add(5);[/B] //  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
    
     
  2. ewaldhorn

    ewaldhorn New Member

    Joined:
    Feb 16, 2010
    Messages:
    36
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    Cape Town, South Africa
    Home Page:
    http://www.javak.co.za
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice