Wrapper Classes

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

No

Wrapper Classes

To put an int into an ArrayList, put the int inside an of an Integer object. Mostly, the job of the wrapper class Integer is to provide objects that contain primitive data. Now the objects (and the primitive data they contain) can be put into an ArrayList or other data structure. The following program builds a list of integers and then writes them out.


import java.util.* ;
class WrapperExample
{
  public static void main ( String[] args)
  {
    ArrayList<Integer> data = new ArrayList<Integer>();

    data.add( new Integer(1) );
    data.add( new Integer(3) );
    data.add( new Integer(17) );
    data.add( new Integer(29) );

    for ( Integer val : data )
      System.out.print( val + " " );

    System.out.println( );
  }
}

The program writes out:

1 3 17 29

The picture emphasizes that the ArrayList contains an array of object references, as always. It shows the ints each contained in a little box that represents the wrapper object.

QUESTION 19:

Would you expect the following to work?

    data.add( 44 );