DEV Community

Cover image for Java Concept of the Day.
ABHINAVA GHOSH (he/him)
ABHINAVA GHOSH (he/him)

Posted on • Edited on

Java Concept of the Day.

Concept for today is Java Generics.

This is a continuation of the series Java Concepts
ORIGINAL POST

Now before we begin , let me tell you that Java Generics Concept will be covered in two parts

part 1 -Introduction , and basics .

part 2 -Advanced Generics.

part 1-Introduction to Generics.

First of all :

What are Generics?

well ,as a java programmer , many times you may have noticed the use of angled brackets <> in java programs mostly in Collections(ArrayList,Set,Map) etc.

Whenever you see <> , means that generics were used here.

Generics in Java were introduced in JSE 5.0(2004)

If you are a Java programmer then type-casting is one of those things which might irritate you the most.
Well Java Generics extend Java's type system to allow ‘a type or method to operate on objects of various types while providing compile-time type safety.’
Generics were introduced to reduce the pain of constantly type-casting variables to make them work correctly.

Lets start with a simple Java Example:

package generics;

public class container {
    String item1;
    String item2;

    public container(String item1, String item2) {
        this.item1 = item1;
        this.item2 = item2;
    }

    public void print()
    {
        System.out.println("container contains: ");
        System.out.println(item1);
        System.out.println(item2);
    }
}
Enter fullscreen mode Exit fullscreen mode

At this stage,the container class is only able to work with String DataTypes.

package generics;
public class app {
    public static void main(String[] args) {
        container container  =new container("java","23");//only string can be passed as a parameter
        container.print();
    }
}

Enter fullscreen mode Exit fullscreen mode

What if we wanted to make this class work with any data type(int,double boolean etc).
To do this we can change the String type to Object type(Because every class is a child class of Object class in Java)

So we can change the code as follows:

package generics;

public class container {
    Object item1;
    Object item2;

    public container(Object item1, Object item2) {
        this.item1 = item1;
        this.item2 = item2;
    }

    public void print()
    {
        System.out.println("container contains: ");
        System.out.println(item1);
        System.out.println(item2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we have made this class kind of "generic" i.e we dont have to worry about typecasting our variables to String before passing them.

package generics;
public class app {
    public static void main(String[] args) {
        container container  =new container(false,23);
        container.print();
    }
}
Enter fullscreen mode Exit fullscreen mode

Hence we just passed an int and a boolean value and it worked flawlessly!

But wait ,there is a problem in this.

Lets introduce some getters in our container class(Shortcut for this is alt+insert).

package generics;

public class container {
    Object item1;
    Object item2;

    public container(Object item1, Object item2) {
        this.item1 = item1;
        this.item2 = item2;
    }

    public Object getItem1() {
        return item1;
    }

    public Object getItem2() {
        return item2;
    }

    public void print()
    {
        System.out.println("container contains: ");
        System.out.println(item1);
        System.out.println(item2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now lets try to get item1 and item2 from our app.java class.

package generics;
public class app {
    public static void main(String[] args) {
        container container  =new container(false,23);
        container.print();
        boolean a= container.getItem1(); //compile error
        int b=container.getItem2();//compile error

    }
}
Enter fullscreen mode Exit fullscreen mode

We get a compile error which says : casting required for boolean and int.
To Solve this we have to again cast them to boolean and int.

package generics;


public class app {
    public static void main(String[] args) {
        container container  =new container(false,23);
        container.print();
        boolean a= (boolean) container.getItem1();//compiled successfully
        int b= (int) container.getItem2();//compiled successfully

    }
}
Enter fullscreen mode Exit fullscreen mode

Thus we still had to type cast it because the container class returns an Object whereas we are collecting it in boolean/int variable.

Remember,we boolean/int variable cannot implicitly accept an Object variable ,but the Object variable can accept ant other datatype.
errors like this will appear : error: incompatible types:

So our class is not Generic till now.
Lets make it Generic:

package generics;

public class container<i1,i2> {
   i1 item1;
    i2 item2;

    public container(i1 item1, i2 item2) {
        this.item1 = item1;
        this.item2 = item2;
    }

    public i1 getItem1() {
        return item1;
    }

    public i2 getItem2() {
        return item2;
    }

    public void print()
    {
        System.out.println("container contains: ");
        System.out.println(item1);
        System.out.println(item2);
    }
}

Enter fullscreen mode Exit fullscreen mode

"i1,i2" are user defined(you can use any names).
So,Basically now we have made it possible for container class to accept any kind of object(as the user wants it to be).

Now lets see the magic!

package generics;

public class app {
    public static void main(String[] args) {

        container<Boolean,Integer> container  =new container<Boolean,Integer>(false,23);
        container.print();
        boolean a= container.getItem1();
        int b=  container.getItem2();

        container<String,Integer> container2  =new container<String,Integer>("java",23);
        container2.print();
        String a2=container2.getItem1();
        int b2=container2.getItem2();
    }
}

Enter fullscreen mode Exit fullscreen mode

See, we have made two different object of the same class 'container' but both of them pass different data types to the same functions

That is the true use of Java Generics.
for every variable of container we dont have to type cast it to boolean/int.
for every variable of container2 we dont have to type cast it to String/int.
Because the java generics take care of it.

So that's it for Java Generics Part1.
Hope you have got a basic understanding of how generics work at the basic level.
In part2 we will be going much deeper into some advanced concepts of Generics.

If you liked this Article then please leave a heart .
And let me know in the comments if you have any suggestions for me.

Top comments (0)