Why do we need generic methods in Java?

1. A Method without Generic Type Assuming you want to write a method that takes two sets and get their intersection. Here is one way to write such a method: public static Set getIntersection(Set set1, Set set2){ Set result = new HashSet();   for(Object o: set1){ if(set2.contains(o)) result.add(o); }   return result; }public static Set … Read more

Why do we need Generic Types in Java?

Generic types are extensively used in Java collections. Why do we need Generic types in Java? Understanding this question can help us better understand a lot of related concepts. In this article, I will use a very short example to illustrate why Generic is useful. 1. Overview of Generics The goal of implementing Generics is … Read more

An example problem of Generic types

The following code has a compilation errors. It is confusing because you think somewhere to find the problem. import java.util.*; abstract class Animal{ public abstract void checkup(); } class Dog extends Animal{ public void checkup(){ System.out.println("Dog checkup"); } } class Cat extends Animal{ public void checkup(){ System.out.println("Cat checkup"); } } class Bird extends Animal{ public … Read more