Type casting and generics in java

delon

Member
Sep 9, 2011
28
0
0
Hello, I am a new programmer trying to learn OOP with Java. I don't know C++. I am having some doubt about the concept of generics.

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

In the above codes, in line 3 why the case (integer) is necessary ? I am adding integer in line 2. It doesn't make sense to me.

What is the advantage of generics ? Please help me!
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
I'm not a Java programmer but it looks like LinkedList is a container for a root object type, not integers. When you store the integer in the container the reference is implicitly converted to a reference to the base class. When you invoke the iterator's next() method it returns a reference to the base class, which needs to be "down cast" back to an integer.

In C# or C++ a "generic" is a type of container that can be instantiated with a type, as in LinkedList<Integer>, so pretty much the opposite of what you have in your example. Beyond that I can't help much but I am sure one of the java developers here will have something to say.
 

beginner99

Diamond Member
Jun 2, 2009
5,320
1,768
136
Hello, I am a new programmer trying to learn OOP with Java. I don't know C++. I am having some doubt about the concept of generics.

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

In the above codes, in line 3 why the case (integer) is necessary ? I am adding integer in line 2. It doesn't make sense to me.

What is the advantage of generics ? Please help me!

Your code is not using generics, that is why it is annoying and the actual point generics where introduced. When creating a generic object you must specify the type when creating that object:

Code:
[b]List<Integer>[/b] myIntList = new [b]LinkedList<Integer>()[/b]; // 1
myIntList.add(new Integer(0)); // 2
Integer x = myIntList.iterator().next(); // no cast needed

where <Integer> can be replaced with any Type (eg. including interfaces).
 

purbeast0

No Lifer
Sep 13, 2001
53,764
6,645
126
Your code is not using generics, that is why it is annoying and the actual point generics where introduced. When creating a generic object you must specify the type when creating that object:

Code:
[b]List<Integer>[/b] myIntList = new [b]LinkedList<Integer>()[/b]; // 1
myIntList.add(new Integer(0)); // 2
Integer x = myIntList.iterator().next(); // no cast needed

where <Integer> can be replaced with any Type (eg. including interfaces).

i also want to add to this, that I'm pretty sure the OP's code will also generate a warning when compiling because you don't give it a type. and while it may run fine and all based on the code you have written, warnings exist for a reason :).

List in java is an interface, and the "types" of lists (such as LinkedList used in the OP) is an object that implements the List interface.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
You probably don't need it, but I'll preface my response with a simple inheritance review.

Basic class inheritance review

Lets say we have the following classes:
Code:
class Animal {
	//code
}

class Cat extends Animal {
	//code
}

Some examples:

Code:
// This is valid because Cat is a sub type of Animal
Animal a = new Cat(); 

// This is not valid 
Cat c = new Animal();

In Java, all classes are sub types of the class Object. Some examples:

Code:
Object myObject = new Cat();

//Now we can't generally assign  the type Object to a Cat
//Cat myCat = myObject; //this is invalid

//but if know the Object is a Cat (as we do with 'myObject'), 
//then we can cast it to a Cat
Cat myCat = (Cat) myObject;

If you cast wrong, you'll get an error when your program executes the cast (it will not error during compilation).

Example:
Code:
Integer myInteger = new Integer(1);

Cat myCat = (Cat) myInteger; //this compiles, but will throw an exception (an error) when it actually executes

My response to your question

I'm going to show you excerpts from the actual Java library source code.

The class LinkedList looks like this:

Code:
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    //a bunch of code
}

The important part is "LinkedList<E>". When you declare your class of LinkedList, you can specify what E is.

For example:

Code:
//A list containing integers
LinkedList<Integer> myIntList = new LinkedList<Integer>();

Whatever you choose for this E, will be used throughout the file.

For example, the get() method in LinkedList is as follows:

Code:
public E get(int index) {
        return entry(index).element;
}

Since we specified E to be Integer, get will return an Integer.

If you don't specify E, then E defaults to Object.

Code:
LinkedList myList = new LinkedList();

So to compare the two:

Code:
//Without generics

LinkedList myList = new LinkedList();
myList.add(123);
Object o = myList.get(0); //returns type Object
// Even though it returns an Object, we know it is really an Integer, 
// so we can cast it from Object to Integer
Integer i = (Integer) myList.get(0);

Code:
//With generics

LinkedList<Integer> myList = new LinkedList<Integer>();
myList.add(123);
Integer i = myList.get(0); //returns type Integer

Short answer

If you don't use generics, your collection will contain Object types. You can put any type into the collection (since all types are subtypes of Object). However, when you retrieve items out of the collections, they will be of type Object, so you'll have to cast them back to their actual type.

If you use generics, you can specify the exact type that the collection will contain.

You should probably always use generics. I can't really think of a good example where you would not want to.

The reason you see code examples without generics is that generics did not always exist.
 
Last edited:

delon

Member
Sep 9, 2011
28
0
0
Thanks a lot :) I have another question.

What does the command line argument mean? As an example..:

public static void main (String[] args)

When I first started learning java, I was not familiar with it. I am introduced with it at the end of the course. As I am learning by myself, I can't ask questions to any instructor or professors. Please anyone explain it.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
It allows you pass parameters into your program from the commandline

Code:
java MyProgram arg0 arg1 ...

An example program
Code:
public class HelloWorld {
	public static void main (String[] args) {
		System.out.println("Hello " + args[0]);
		System.out.println "Your last name is " + args[1]);
	}
}

Running the program like this:
Code:
java HelloWorld John Smith

will output

Code:
Hello John
Your last name is Smith
 

beginner99

Diamond Member
Jun 2, 2009
5,320
1,768
136
@Leros Thanks man! You are awesome. Do you know parallel programming ?

I would first learn the basics of java, then basics of " parallel programming" in java (google join(), wait(), notify(), notifyAll()) and then have a look at java.util.concurrency package.

EDIT:

Some fundamental knowledge on how operating systems work would not hurt either to understand certain principles of parallel programming.
 

delon

Member
Sep 9, 2011
28
0
0
I found this forum very helpful. Is there any other forums for discussing about Computer Architecture ? I mean the hardware side of computer. I didn't find any place where I can post the questions related to comp arch anandtech.

I am having some doubt related to pipeline and non-pipelined processors.
 

Broheim

Diamond Member
Feb 17, 2011
4,587
3
81
I found this forum very helpful. Is there any other forums for discussing about Computer Architecture ? I mean the hardware side of computer. I didn't find any place where I can post the questions related to comp arch anandtech.

I am having some doubt related to pipeline and non-pipelined processors.

the CPU subforum should answer all your question (you might have to fight your way through a couple of fanboys though)