[ Published on -
1. Java - Primitives
2. Java - Strings
3. Java - Arrays
4. Java - Date
5. Java - Generics
6. Java - Collections
7. Java - Localization
8. Java - Formatting
9. Java - Regular Expressions
10. Java - System
11. Java - Serialization
12. Java - Multithreading
13. Java - IO/File
14. Java - Networking
15. Java - ORM - JPA
a) Simple User entity class
package basics.basicsExamples;
import java.util.Arrays;
/** ****************************************************************************
* GENERICS EXAMPLE CLASS
* @author stanislav.zorjan
*/ public class GenericsExample {
String[] str = new String[]{"one", "two", "three", "four"};
Integer[] integer = new Integer[] {1, 2, 3, 4};
String str0 = "Simple String";
Integer integer0 = 1;
/** ************************************************************************
* Default constructor
*/
public GenericsExample() {
printValues(str);
printValues(integer);
System.out.println("");
System.out.println(printType(new Integer(10)));
printString(str0);
printInteger(integer);
TestClass<String> gs = new TestClass<String>();
gs.add(str0);
System.out.println(gs.get());
TestClass<Integer[]> gi = new TestClass<Integer[]>();
gi.add(integer);
System.out.println(Arrays.toString(gi.get()));
printTestInterface(gi);
SimpleClass si = new SimpleClass();
si.add(str);
printStringAndTi(si);
}
// accepts any array type and print its value
private <T> void printValues(T[] arr){
System.out.println(Arrays.toString(arr));
}
// accepts any type, prints type class and returns same type
private <T> T printType(T t){
System.out.println(t.getClass());
return t;
}
// accepts only types String types
private <T extends String> void printString(T t){
System.out.println(t);
}
// accepts only Integer array types
private <T extends Integer> void printInteger(Integer[] t){
System.out.println(Arrays.toString(t));
}
// accepts only types that implements TestInterface interface
private <T extends TestInterface> void printTestInterface(T t){
t.test();
}
// accepts only String types that implements TestInterface interface
private <T extends SimpleClass & TestInterface> void printStringAndTi(T t){
t.test();
}
}
/** ****************************************************************************
*
* @author stanislav.zorjan
* @param
*/
class TestClass<T> implements TestInterface{
private T t;
@Override
public void test(){
System.out.println(this.t.getClass());
}
public void add(T t){
this.t = t;
}
public T get(){
return this.t;
}
}
/** ****************************************************************************
*
* @author stanislav.zorjan
*/
class SimpleClass extends TestClass{ }
/** ****************************************************************************
*
* @author stanislav.zorjan
*/
interface TestInterface{
public void test();
}