Shailendra Patel
Shailendra Patel

Reputation: 128

Java Generic Type and Object Class

I need to know what is the difference between java Generic type and Object class. Here are two codes and both works fine, I just need to know what is the difference between them :

Program 1 using Object Class: package a;

public class Generic {
    private Object[] datastore;
    private int size;
    private int pos;

    public Generic(int numEl) {
        size = numEl;
        pos = 0;
        datastore = new Object[size];
    }

    public void add(Object a){
        datastore[pos] = a;
        pos++;
    }

    public String toString(){
        String elements ="";
        for (int i=0; i<pos; i++) {
            elements += datastore[i] + " ";
        }

        return elements;
    }
}

Program 2 using Generic Type: package a;

public class Generic<T> {
    private T[] datastore;
    private int size;
    private int pos;

    public Generic(int numEl){
        size = numEl;
        pos = 0;
        datastore = (T[]) new Object[size];
    }

    public void add(T a) {
        datastore[pos] = a;
        pos++;
    }

    public String toString(){
        String elements ="";
        for (int i=0; i<pos; i++) {
            elements += datastore[i] + " ";
        }

        return elements;
    }
}

Upvotes: 0

Views: 1122

Answers (3)

Ernusc
Ernusc

Reputation: 526

When type erasure begins, compiler replaces all parameters to it top bounds. For example:

class Example<T> {}

will become

class Example<Object> {}

If you define parameter with bounds, it will be something like that:

class Example<T extends Number> {} 

will become

class Example<Number> {}

Essentially, your two examples are generic: one with a pre-defined type "Object", and the second one with T extends Object type which is more concrete and secured than the first one. With the latter, you avoid unnecessary casts

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68915

Genercis is compile time concept to ensure type safety. At runtime

private T[] datastore;

will be interpreted as

private Object[] datastore;

So you can say

Generic generic = new Generic(2);
generic.add("test"); //allowed

but you cannot say

Generic<Integer> generic = new Generic<Integer>(2);
generic.add("test");  // compiler error

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Due to Type Erasure, the technique used to implement generics in Java, there is no difference between these code snippets at runtime.

However, at compile time the second code snippet provides better code safety.

For example, it ensures that all objects inside the array datastore have the same type. The first snippet lets you add objects of different type to datastore, because all objects derive from Object. The second snippet, however, requires that all calls to add were supplying objects compatible with type T, the generic type parameter of the class.

Upvotes: 3

Related Questions