minte9
LearnRemember



Type

There is nothing particulary complex about the concept of generic types.
 
/**
 * A generic type is a special kind of variable ...
 * with whatever type you pass in.
 */

package com.minte9.collections.generics;

public class Type {

    public static void main(String[] args) {
        
        A a = new A();
        a.set(10);
        System.out.println(a.get()); // 10
        a.set("John");
        System.out.println(a.get()); // John

        Box<Integer> b = new Box<>();
        b.set(10);
        System.out.println(b.get()); // 10
        // b.set("John"); // Error: not applicable ...
    }
}

class A { // non generic class

    private Object obj;
    public void set(Object o) { 
        obj = o;
    }
    public Object get() { 
        return obj; 
    }
}

class Box<T> { // generic class (type)
        
    private T t;
    public void set(T t) { 
        this.t = t; 
    }
    public T get() { 
        return t; 
    }
}

Multiple

You can use multiple generic type parameters.
 
/**
 * A generic type may have multiple type parameters.
 * Each parameter must be unique.
 */

package com.minte9.collections.generics;

public class Multiple {
    public static void main(String[] args) {
        
        Box<Integer, Integer> box = new Box<>();
        box.set(10);
        System.out.println(box.get()); // 10
    }

    static class Box<T, U> {

        private T t;
        public void set(T t) { 
            this.t = t; 
        }
        public T get() { 
            return t; 
        }
    }

    // static class Word<T, T> {} // Error: Duplicate type parameter T
}

Limitations

Generics types cannot be static (or used with primitives).
 
/**
 * Generic type params can't be static.
 *
 * Because static field is shared by all objects ...
 * what's the actual type of t?
 * 
 * Generics cannot be used with primitives.
 */

package com.minte9.collections.generics;

public class Limitations {
    public static void main(String[] args) {
        
        Box<Integer> b1 = new Box<>();
        Box<String> b2 = new Box<>();

        System.out.println(b1.hashCode());
        System.out.println(b2.hashCode());
        
        // Box<int> box = new Box<int>(); // not allowed!
    }

    static class Box<T> {

        //static T t; // Error: static reference to non-static T
    }
}



  Last update: 471 days ago