In the last few lectures, we saw Generics in programs, and today we’re going to focus on Generics.
Here’s what generics do: They were designed to extend Java’s type system, allowing one type or method to manipulate objects of different types while providing compile-time type safety. The two uses of generics are clearly indicated here: one is to allow a class or method to manipulate objects of different types, and the other is to provide compile time type safety. This was introduced in Java 5. This is the result of the Java design team moving with The Times and coming to terms with history, and it’s basically there, but it’s far from perfect, and the industry is getting mixed reviews.
To understand this concept, let’s start at the beginning and look at how we wrote programs without generics.
Write a simple program to print an array of data and strings as follows (OverwriteTest. Java) :
public class OverwriteTest { public static void printArray(Double[] dArray) { for (Double d : dArray) { System.out.println(d); } } public static void printArray(String[] sArray) { for (String s : sArray) { System.out.println(s); }} public static void main(String args[]) {Double[] dArray = {1.618, 2.71828, 3.14159};