Java Generics in layman language

List integers = new ArrayList();
integers.add(1);
integers.add(2);
integers.add("three");
for(int i=0;i<list.size();i++) {
if(list.get(i) == (Integer)list.get(i)) {
System.out.println(2*(Integer)list.get(i));
} else {
System.out.println(1);
throw new IllegalArgumentException("Value is not integer");
}
}
public static void main(String[] args) {
Set data = new HashSet();
Set updatedData = getData(data);
}
public static Set getData(Set data) {
data.add(1);
data.add("Two");
data.add(new ArrayList<>());
return data;
}
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add("three"); // compile time exception
List<Integer> list1 = new ArrayList<>();List list2 = new ArrayList<>();
public class GenericClass<T,E> {
private T key;
private E value;
}
GenericClass<Integer,Integer> integers = new GenericClass<>();
GenericClass<String,Integer> strings = new GenericClass<>();
public interface GenericInterface<T,E> {
T firstMethod();
E secondMethod();
}
public class SampleClass implements GenericInterface<Integer,String> {
@Override
public Integer firstMethod() {
return null;
}
@Override
public String secondMethod() {
return null;
}
}
public <T,E> void genericMethod(T key,E value) {
System.out.println(key);
System.out.println(value);
}
public static <T> Map<T,T> staticGenericMethod(T val1,T val2) {
Map<T,T> map = new HashMap<>();
map.put(val1,val2);
return map;
}
public <T> Map<T,T> staticGenericMethod(T val1,T val2) {
Map<T,T> map = new HashMap<>();
map.put(val1,val2);
return map;
}
public class ClassWithGenericConstructor<T> {
private T key;
private T value;
public ClassWithGenericConstructor(T key,T value) {
this.key = key;
this.value = value;
}
}
public class ClassWithGenericConstructor {
public <T> ClassWithGenericConstructor(T key,T value) {
System.out.println(key);
}
}
public class GenericArray<T> {
// this one is fine
public T[] notYetInstantiatedArray;
// causes compiler error; Cannot create a generic array of T
public T[] array = new T[5];
}
Collection<?> coll = new ArrayList<String>();
List<? extends Number> list = new ArrayList<Long>();
Pair<String,?> pair = new Pair<String,Integer>();
Collection<?> coll = new ArrayList<String>();
List<? extends Number> list = new ArrayList<Long>();
List<? super Integer> list = new ArrayList<Number>();
private static T member; //This is not allowed
new  T();   // not allowed
List<int> ids = new ArrayList<>();    //Not allowed
public class GenericException<T> extends Exception {}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store