Java Reference
In-Depth Information
In our example, the ArrayList class takes as input the Employee class. This means that
the array list can store inside it only employees. If we try to insert an object of a different
type in the ArrayList , then an error will occur. Note that, starting with Java 7, the above
syntax can be simplified as follows.
ArrayList < Employee > emps = new ArrayList <> () ;
The second reference to the Employee class is redundant, and therefore can be omitted.
Note that a generic class can take as input only the name of a class and not the name of a
primitive type. For example, the following code will not compile.
ArrayList < int > dice = new ArrayList < int > () ;
However, we can use the wrapper Integer class as input to the ArrayList class. For
the most part, an Integer object behaves exactly like an int , but it is still an object.
Therefore, an ArrayList of integers can be declared as shown below.
ArrayList
<
Integer
>
dice = new ArrayList
<>
() ;
A common mistake by novice programmers is to specify the size of the ArrayList as
a parameter in the parentheses. However, this is the wrong approach because we do not
need to specify the size of an ArrayList when we create it. The size of an ArrayList is
dynamically determined by the number of objects that is stores. Therefore, a newly created
ArrayList will always have size of zero.
7.2 Immutable Objects
Consider the following code.
class Test {
public static void inc(Integer i ) {
i ++;
}
public static void main(String [] args) {
Integer i=3;
inc( i ) ;
System.out.println(i);
}
}
The behavior of the code is very interesting and counterintuitive. Note that the code:
Integer i = 3 is rewritten by Java to: Integer i = new Integer(3) . Therefore, as Fig-
ure 7.1 suggests, a new object is created inside the main method. Let the location of the
new object be 2000. Next, this object is passed as a parameter to the inc method. Recall
that only the object's address will be passed to the inc method. Now the variable i inside
the inc method will be initially equal to 2000. However, if we try to display the variable,
then we will see the number 3. The reason is that the Integer class contains a toString
method that returns the integer that is stored inside the class.
Next, let us examine the statement i++ . This is where all the magic happens! This code
is equivalent to i=i+1 , which in turn means change the value inside the i object to 4.
However, the Integer classisimmutable.
 
Search WWH ::




Custom Search