Eli
Eli

Reputation: 857

Generics Vs. Arraylist?

I am a little confused regarding ArrayLists and generics, for instance, in the program below when I declared, Gen<Integer>iOb=new Gen<Integer>(88); it declared a generic type of Integer correct? However, if I declare an arraylist in the same fashion? In the case of an arraylist, it is the type that is in angle brackets, however, researching generics, it says that the type in the angle brackets is the generic type? How do I know if its an arraylist of a class type or a generic?

//A simple generic class 
//Here, T is a type parameter that
///will be replaced by a real type
//when an object of type gen is created
class Gen<T> {
    T ob;//declare an object of type T

    //Pass the constructor a refernce to
    //an object of type T 
    Gen(T o) {
        ob = o;
    }

    //return ob
    T getob() {
        return ob;
    }

    //show type of t
    void showType() {
        System.out.println("Type of T is " + ob.getClass().getName());
    }
}

class GenDemo {
    public static void main(String[] args) {
        //create a gen reference for integers
        Gen<Integer> iOb;
        //Create a Gen<Integer>Object and assign its 
        //reference to iob, notice the use  of autoboxing
        //to encapsulate the value 88 within an integer object 
        iOb = new Gen<Integer>(88);

        //show the type off data used by iob 
        iOb.showType();
        //get the value in Iob notice that no cast is needed
        int v = iOb.getob();
        System.out.println("Value: " + v);
        System.out.println();
        //create a gen object for strings
        Gen<String> strOb = new Gen<String>("Generic Test");
        //show the type of data 
        strOb.showType();
        //get the value of strOb, again notice that no cast is needed 
        String str = strOb.getob();
        System.out.println("Value  :" + str);
    }
}

Upvotes: 0

Views: 1695

Answers (4)

Chris Gong
Chris Gong

Reputation: 8229

First, we should clear up some terms. From https://docs.oracle.com/javase/tutorial/java/generics/why.html

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

So when you did Gen<Integer>iOb=new Gen<Integer>(88);, a Gen class was made of type Gen but with generic type parameter Integer. Gen is a generic class because the class header contains a generic type parameter <T>. However, Arraylists are also generic classes because they are not restricted to one type as you can tell from the declaration. When declaring a Arraylist, you can do a type declaration the same way you do so for your Gen class. Ex: Arraylist<String> list = new ArrayList<String>();

Arraylists do have a raw type implementation which does require not a type parameter in the declaration. Ex: Arraylist list = new Arraylist(); But this is not recommended and Java will actually give you a warning if you declare arraylists this way, advising you to parameterize the arraylist.

In conclusion, a generic type is a generic class or interface that is parameterized over types (https://docs.oracle.com/javase/tutorial/java/generics/types.html). So your Gen class and the built-in Arraylist class of Java are both generic types.

Upvotes: 1

djmoneystax
djmoneystax

Reputation: 21

Your question is worded kind of strange, but I'll give it a shot. Generics are used for type safety, ESPECIALLY for collections. If you were to declare an ArrayList like this:

ArrayList a= new ArrayList(); 

then you could put any kind of object you wanted in to the ArrayList. That's very dangerous since when you're retrieving objects from the list you'll need to know what kind of object you will be retrieving from the list. You wouldn't want to pull a cat object into a person reference! Cats aren't people! That's where generics come in. Declaring your ArrayList like this:

ArrayList<People> p= new ArrayList<People>(); 

allows you to have type safety. No more problems with those pesky Cat objects getting in to your people array!

As for this:

//get the value in Iob notice that no cast is needed

int v = iOb.getob();

You seem to be getting confused with unboxing. It has nothing to do with Generics. I recommend you look up autboxing and unboxing.

finally:

  //get the value of strOb, again notice that no cast is needed

    String str = strOb.getob();

I don't see what you don't understand here. Strings are objects. You put a String object in and you pulled a String object out.

I also recommend creating a simple java object, say a person, so you can create a generic with your Gen class, say String, and attempt to put a Person object in. See what errors it gives.

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180113

You seem to be confusing the concepts of a generic type and a type parameter.

Given your class:

class Gen<T> {
    // ...
}

Gen is a generic class (a specific kind of generic type) because it is declared to have at least one type parameter, in this case T. When you instantiate Gen, and sometimes in other cases, you provide a type expression that is bound to T:

Gen<?> gen = new Gen<String>();

The type expressions given (? and String) are typically also called "type parameters", just like the T in class Gen's definition. Specific type parameters may be formed from generic classes (example: List<String> in Gen<List<String>>), but "generic class" is not a synonym for "type parameter".

ArrayList is just the same. It is a generic class with one type parameter. Specific declarations provide type expressions to serve as the values of those type parameters:

List<Integer> list = new ArrayList<Integer>();

There, List<E> and ArrayList<E> are generic types; the latter is specifically a generic class. The Integer on both sides is the type parameter applying to the declaration of list and the instantiation of ArrayList; it is not referred to as a "generic class" in this context or any other.

Upvotes: 4

AJNeufeld
AJNeufeld

Reputation: 8695

When I declared, Gen<Integer> iOb = new Gen(88); it declared a generic type of Integer correct?

This is incorrect. You are declaring/creating an Gen object, which holds a T extends Object. Inside Gen code, you can only use functions that are allowed to be used on an Object, such as getClass().

The Java Compiler remembers that iOb will reference a Gen object that must hold an Integer object, and will generate automatic type casting on the return value of getob() ...

int v=iOb.getob();

Is interpreted by the compiler as if the following was written:

int v = (Integer) iObj.getob();

Where getob() is considered to just return an Object. Note that this is a compile-time transformation as a convenience for the programmer.

However, if I declare an arraylist in the same fashion? In the case of an arraylist, it is the type that is in angle brackets, however, researching generics, it says that the type in the angle brackets is the generic type? How do I know if its an arraylist of a class type or a generic???

class SomeClass<T> { ... } declares a generic type. The part between the angle brackets is the "type argument(s)" for the generic class.

When the generic class used as a type for a variable, it is considered a specialization of the the generic class, and type argument(s) could be a concrete class, an interface, or another generic class.

Upvotes: 2

Related Questions