Java Reference
In-Depth Information
System.out.println(p.toString());
}
Map<String, String> strMap = new HashMap<>();
strMap.put("first", "Josh");
strMap.put("last", "Juneau");
System.out.println(strMap.values());
}
}
Note When we talk generally about a collection or a collection type , you can read
this as those types that make up the Java Collections Framework. This includes all the
classes and interfaces that descend from the Collection and Map interfaces. Collec-
tion types generally refer to types that descend from the Collection interface.
How It Works
The solution code demonstrates some basic use-cases for generics. The examples in the
GenericsDemo.java file, contained within the recipe sources, go into more detail
to demonstrate the use of generics with Java collections versus showing you how to
create generic types. Unless you are developing a library API, you probably won't be
creating your own generic types. However, if you understand how generics are used
with the Collection interfaces and classes, you will have the knowledge you need
to create your own generic types.
The first thing to understand and remember about Java generics is that they are
strictly a compile-time feature that aids the developer in creating more type-safe code.
All the type information that you specify when you parameterize a generic type gets
“erased” by the compiler when the code is compiled down to byte code. You'll see this
described as type erasure . Let's look at an example of a generic Collection type:
the List. List is an interface defined as follows:
public interface List<E> extends Collection<E> { ... };
To specify the element type for a List (or any Collection type), simply in-
clude the type name in angle brackets when declaring and instantiating objects. When
you do this, you are specifying a “parameterized type.” The following code declares
Search WWH ::




Custom Search