Java Reference
In-Depth Information
int sum = 0;
for (int n : list) {
sum += n;
}
System.out.println("list = " + list);
System.out.println("sum = " + sum);
This code produces the following output:
list = [13, 47, 15, 9]
sum = 84
The code takes advantage of a mechanism that Java provides for simplifying code
which involves the use of wrapper classes. For example, Java will convert between
Integer values and int values for you when your intent seems clear. Given the dec-
laration of the variable list as an ArrayList<Integer> , Java would normally
expect you to add values of type Integer to the list. But in the preceding code you
were adding simple int values, as in:
list.add(13);
When it reaches this line of code, Java sees that you are adding an int to a struc-
ture that is expecting an Integer . Because Java understands the relationship between
int and Integer (each Integer is simply an int wrapped up as an object), it will
automatically convert the int value into a corresponding Integer object. This
process is known as boxing.
Boxing
An automatic conversion from primitive data to a wrapped object of the
appropriate type (e.g., an int boxed to form an Integer ).
Similarly, you don't have to do anything special to unwrap an Integer to get the
int inside. You could write code like the following:
int product = list.get(0) * list.get(1);
This code multiplies two values from the ArrayList<Integer> and stores the
result in a variable of type int . The calls on get will return an Integer object, so
normally these values would be incompatible. However, because Java understands
the relationship between int and Integer it will unwrap the Integer objects for
you and give you the int values stored inside. This process is known as unboxing.
Unboxing
An automatic conversion from a wrapped object to its corresponding primi-
tive data (e.g., an Integer unboxed to yield an int ).
 
Search WWH ::




Custom Search