[DATA STRUCTURE & Other Objects Using JAVA] Chapter 5 Generic Programming

5.1 Java’s Object Type and Wrapper Classes

  • Java has an important built-in data type called Object. AnObject variable is capable of holding a reference to any kind of object.

5.1.1 Widening conversion

Suppose x and y are reference variables. An assignment x = y is a widening conversion if the data type of x is capable of referring to a wider variety of things than the type of y.

5.1.2 Narrowing conversion

Suppose x and y are reference variables, and x has a smaller ability to refer to things than y. A narrowing conversion using a typecast can be made to assign x from y.

Narrowing conversions also occur when a method returns anObject and the program assigns that Object to a variable of a particular type.

5.1.3 Wrapper Classes

  • Wrapper class: A wrapper class is a class in which each object holds a primitive value.
  • Boxing conversion: placing an integer into an Integer object.
  • Unboxing conversion: taking back out an integer form an Integer object.

5.2 Object Methods and Generic Methods

Object Methods

There are some potential type errors that can’t be caught until the program is running.

Generic Methods

A generic method is a method that is written the types of the parameters not fully specified.

  • T is called the generic type parameter.
  • Single capital letters such as T for “type”, and E for “element”.
  • The generic type parameter always appears in angle brackets right before the return type of the method.
  • When a generic method is activated, the compiler infers the correct class for the generic type parameter.
  • A generic method allows any class for the argument, and the compiler can detect certain type errors.
  • The generic type parameter is similar to id in Objective-C.
  • Generic methods with more than one generic type parameter.

  • The data type inferred by the compiler for the generic type must always be a class type.

  • You may not call a constructor for the generic type, nor may you create a new array of elements of that type.

5.3 Generic Classes

5.3.1 Writing a Generic Class

When an entire class depends on an underlying data type, the class can be implemented as a generic class, resulting in the same typechecking advantages that you have seen for generic methods.

  • The single capital letter ‘E’ indicates that it is the unknown class of an “element” in the bag.
  • Programs cannot creates arrays where the components are the generic type parameter.

5.3.2 Using a Generic Class

  • A program that wants to use a generic class must explicitly specify what class will be used for the generic type parameter. This process is called instantiating the generic type parameter.

  • You cannot add a String object to a bag of Integer objects.

5.3.3 Creating an Array to Hold Elements of the Unknown Type

  • Within the generic class implementation, we are not allowed to create a new array of objects of the unknown type E.
  • The solution is to declare data as an array of Java Objects.

5.3.4 Retrieving E Objects from the Array

Whenever we retrieve a component of the array, we must apply a typecast to the type E.

This typecast (E) is one of several places where Java compilers issue warnings about possible errors that can occur at run time.

5.3.5 Warning in Generic Code


During the runtime, the information about the actual data type of a generic object is always unavailable. Therefore there is no way for the program to check whether the typecast is correct. The warning that Java produces in this situation is an “unchecked cast” warning. This means that if the typecast is illegal at run time, then the error will not be caught as it usually is.

Variable Arity Methods

Variable arity methods will cause the compiler to create an array of generic object, which usually is forbidden because it can result in unchecked typecast errors.

Suppressing Unchecked Warnings

There is no semicolon after this annotation, and the line can be placed by itself just prior to any method declaration.

  • Available since Java 1.7
  • It can suppresses both warning at the declaration of the variable arity method and the warning that sometimes occur when the variable arity method is activated.
  • Only available to static or final methods.

5.3.6 Using ArrayBag as the Type of a Parameter or Return Value

All the uses of the ArrayBag data type within its own implementation will be written as ArrayBag<E>.

5.3.7 Generic Collections Should Use the equals Method

When a generic collection tests for the presence of a non-null elements, it should generally use the equals method rather than the == operator.

5.3.8 Set Unused Reference to null

When a collection class is converted to a generic collection class, make sure any unused reference variables are set to null. This usually occurs in methods that remove elements from the collection. Setting these variables to null will allow Java to collect any unused memory.

5.3.9 Steps for Converting a Collection Class to a Generic Class

1. The Name of the Class

  • Convert all IntArrayBag to ArrayBag<E>.
  • The name of the constructor is just ArrayBag.

2. The Type of the Data Array

3. The Type of the Underlying Element

Find all the remaining spots where the old classes used int to refer to an element in the bag, and change them to the generic type parameter.

4. Change Static Methods to Generic Static Methods

Any static method that depends on the generic type E must be changed to a generic method, which means that <E> appears just before the return type in the method’s heading.

5. Use Typecasts When an Element Is Retrieved from the Array

return (E)data[i];

6. Suppress Warning

Some code in generic collection classes generates “unchecked” warnings. Examine each of these spots and suppress the warning.

7. Updated Equality Tests

Use the method equals() instead of ==.

8. Decide How to Treat the null Reference

  • Allow the null reference to be placed in the bag, and indicate this in the documentation.
  • Some of the bag’s methods will need special cases to deal with null references.
  • Such as the countOccurrences() will search for a null target using “==”, but non-null target is counted by using its equals method.

9. Set Unused Reference Variable

10. Update All Documentation

5.4 Generic Nodes

  • In general, the equals method may be used only when you know that the target is non-null.
  • When the purpose of a boolean expression is to test whether two references refer to the exact same object, then use the “==” or “!=” operator.

5.5 Interfaces and Iterators

  • A Java interface is primarily a list of method that a programmer may want to implement in a single class.
  • A class that has implemented the methods of a interface is said to implement the interface.

5.5.1 How to Write a Class That Implements an Interface

1. Read the documentation that is provided for the interface.

2. Tell the compiler that you are implementing an interface.

  • The keyword implements informs the compiler that you are implementing the interface.
  • If a class implements several difference interfaces, then the names of the interface appear one after another, separated by comma.

3. Implement the class in the usual way.

Make sure that each of the specified methods is implemented.

5.5.2 Generic Interfaces and the Iterable Interface

  • A generic interface specifies a list of methods that depend on one or more unspecified classes.
  • Interface Iterator<E>

  • remove() removes the element that was given by the most recent call to next().

  • Sometimes an iterator does not allow elements to be removed. In this case, activating the remove() method results in an UnsupportedOperationException.

5.5.3 The Comparable Generic Interface

  • Java has a generic interface called Comparable<T> that requires just one method:

  • x.compareTo(y): The method returns an integer that is negative (if x is less y), zero (if x and y are equal), or positive (if x is greater than y).

5.5.4 Parameters That Use Interfaces

When an interface name is used as the type of a method’s parameter, the actual argument must be a data type that implements the interface.

5.5.5 Using instanceof to Test Whether a Class Implements an Interface

variable instanceof interface-or-class-name

5.5.6 The Cloneable Interface

  • There are no methods specified in the Cloneable interface. (What the fuck?!)
  • object.clone()

    1. Check to see whether the class has implemented the Cloneable interface. If not, a CloneNotSupportedException is thrown.
    2. Otherwise, the clone is make by copying each of the instance variable of the original.

5.7 The Java Collection Interface and Map Interface

Map: A map is a collection class in which key/value pairs may be added. A pair can be retrieved or removed by specifying just its key. This is similar to NSDictionary in Objective-C.

3 thoughts on “[DATA STRUCTURE & Other Objects Using JAVA] Chapter 5 Generic Programming

  1. I was curious if you ever considered changing the layout of your blog?
    Its very well written; I love what youve got to say. But maybe you
    could a little more in the way of content so people could
    connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures.
    Maybe you could space it out better?

    • Yeah. That’s a big problem. I was just summarizing what I learned from the materials. I agree with you that pictures are important. They are super helpful for others to understand what I am talking about and the knowledge. As for the layout of the blog, I am not thinking about making big changes toward it. Probably I will do it in the future.

      • I want to thank the blogger very much not only for this post,but also for his all prveuois efforts.I found this Google search to be greatly interesting.I will be coming back to your site for more information. startIndex

Leave a Reply

Your email address will not be published. Required fields are marked *