0

I am in a data structures class and have had about a year and half of experience with JAVA. I am trying to understand code which is not clearly defined in the book. In the following line:

 Queue<Integer> encodingQueue = new LinkedList<Integer>();

I understand that we are creating a new LinkedList object of Queue type. My questions are:

  1. what is the <> used with Integer for? And why is it also with the LinkedList object and not in the parameters?
  2. Why is the word Integer used and not int?

Thanks!

tom
  • 354
  • 4
  • 15
Hermes Trismegistus
  • 515
  • 2
  • 5
  • 16

8 Answers8

3

http://docs.oracle.com/javase/tutorial/java/generics/

  1. Used to specify type parameters. It's how you pass a type into a class. Lists/queues have them, because it's the type of Object that the list holds.

  2. Integer is used instead of int because ints are not Objects. Integer is just the wrapper class for it.

Cruncher
  • 7,641
  • 1
  • 31
  • 65
  • `Integer` is not an `Object` either. It **is** are reference type. – Sotirios Delimanolis Sep 13 '13 at 17:41
  • 2
    `System.out.println(new Integer(5) instanceof Object);` prints true, so it's an Object for all intents and purposes. – Cruncher Sep 13 '13 at 17:43
  • The interface `Type` is not an `Object` and you can pass that as a generic type argument. – Sotirios Delimanolis Sep 13 '13 at 17:44
  • @SotiriosDelimanolis Uh? `Integer` is an `Object`, and a wrapper class around an `int` value. – Laf Sep 13 '13 at 17:45
  • @Laf The reason `Integer` can be passed and not `int` is not because the `Integer` class extends `Object`. – Sotirios Delimanolis Sep 13 '13 at 17:47
  • @Sotirios `Integer` extends `Number`, and `Number` extends `Object`. Where did you see this `Type` interface? – Laf Sep 13 '13 at 17:48
  • 1
    @SotiriosDelimanolis It is however, because all things that are Integers are also Objects. The same way that all things that are Types are Objects – Cruncher Sep 13 '13 at 17:48
  • @Laf I believe he's referring to `java.lang.reflect.Type` which is an interface that primitive types technically implement. – MrLore Sep 13 '13 at 17:49
  • The JLS states: [`Type arguments may be either reference types or wildcards`](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.5.1). That is the reason it can accept `Integer` and not `int`. – Sotirios Delimanolis Sep 13 '13 at 17:49
  • Why can't we downvote comments? :-/ @SotiriosDelimanolis: "reference type" is anything that is not a primitive. `Object` is the root of the hierarchy for reference types, so all reference types are `Object`. – vanza Sep 13 '13 at 17:52
  • @vanza interfaces are not Objects, but every instance of an interface is also an instance of an object – Cruncher Sep 13 '13 at 17:53
  • @vanza Yes, it currently is. But if that changes in the future, it won't affect the Java Language Spec for what can be passed as a type argument. Use the proper jargon when answering technical questions. – Sotirios Delimanolis Sep 13 '13 at 17:55
  • @Cruncher: since interfaces are not instantiable that differentiation is hardly useful. `Object.class.isAssignableFrom(java.util.Collection.class)` results in `true`. – vanza Sep 13 '13 at 17:55
  • @SotiriosDelimanolis if they ever make an `object` which is not an `Object`, then you'll never see me around the Java tag again, I can assure you that. – Cruncher Sep 13 '13 at 17:58
  • @Cruncher They can refactor and call it `Thing` instead. Then your answer as it stands would be incorrect. If you used `reference type` it would still be correct. – Sotirios Delimanolis Sep 13 '13 at 17:59
  • @SotiriosDelimanolis They could also change the language spec that you referenced, in which case YOUR answer would be incorrect? The assertion "You're wrong if they did it differently" doesn't stand to reason. – Cruncher Sep 13 '13 at 18:00
  • @SotiriosDelimanolis: your hypothetical scenario goes against the document yourself linked to; read section 4.3.2. – vanza Sep 13 '13 at 18:04
3

good luck in your data structures class!

Generics

In Java, these data structures (i.e. Queue, LinkedList, ...) can hold any kind of object. More often than not, though, a given instance of a Queue or LinkedList will hold a collection of the same type (here integers).

The angle-bracket syntax is used to specify which types are allowed in this specific instance of the collection.

So, the way to read:

Queue<Integer> encodingQueue = new LinkedList<Integer>();

is...

"Create a new linked-list that holds only integers, and assign that instance to the reference variable 'encodingQueue' which will be treated like a queue that holds only integers."

This feature that you're using is called "Generics". You can read up more about it here: http://en.wikipedia.org/wiki/Generics_in_Java

Autoboxing

In Java, there are two kinds of types: primitives and object references. "int" is a primitive and "Integer" is a class.

You cannot create a reference to a primitive in Java and collections (like LinkedList) only hold object references. So, you cannot stuff a primitive into a collection (e.g. you cannot put "int"s into a LinkedList). This is why Java provides the object equivalent for primitives: so that you can create collections of things like integers, floats, booleans, etc.

It can be a little confusing when you first start using primitives; Java will attempt to automatically convert primitives to object references when that's what's clearly needed (and vice-versa). This feature is called "autoboxing".

List myList = new LinkedList<Integer>();
myList.add(2);

Here, 2 is a primitive. But the compiler knows that you need an object reference, not a primitive. So, it automatically "boxes-up" this value by (in the background) creating a new instance of the class Integer and setting it's value to 2.

So, that's equivalent to (and this is what actually happens):

List myList = new LinkedList<Integer>();
myList.add(Integer.valueOf(2));

Where Integer.valueOf() first looks in an internal cache to see if an instance already exists for that value. If it does, that's returned, otherwise a new Integer object for that value is created. (Thank you, Boris, for pointing this out)

JTigger
  • 394
  • 2
  • 10
  • Very nice answer! Exactly right! Have a +1 and Welcome to StackOverflow! – sparks Sep 13 '13 at 18:02
  • 1
    Not quite - similar to `String`s Java has a cache of wrapper values. By constructing a `new Integer` rather than auto boxing a new instance is created rather than one taken from the cache. – Boris the Spider Sep 14 '13 at 14:33
  • Thank you, Boris! I updated the answer to reflect what _actually_ happens. – JTigger Sep 14 '13 at 15:05
2

Integer is a object based wrapper version of the primitive 'int'. This allows the basic type to play well in object oriented language. Read more here:

They can be used interchangably native and wrapper, this is called 'autoboxing/unboxing' http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

The <> are part of Java Generics (A way to tell the compiler what object you expect to work with), more here:

http://docs.oracle.com/javase/tutorial/java/generics/

Happy learning!

JGreenwood
  • 21
  • 1
0
  1. That infers the type of object to be stored in the Queue. You'll want to look into Java Generics.

  2. Collections store objects, int is a primitive type, Integer is the Java object representation. The compiler will autobox any ints you attempt to put in the Queue as Integers.

TheClair
  • 721
  • 4
  • 8
0

1) <Integer> is used to specify at compile-time that the objects contained in your Collection are going to be Integers, so for instance this will not compile:

Double d = 10d;
encodingQueue.add(d); <-- Compilation error

2) The reason why Integer is used instead of int is that you cannot store into collections primitive data types but you have to use objects; you can still write encodingQueue.add(10) thanks to the automatic boxing of ints inside Integers, but when you declare a typed collection (or, in general, a parameterized class) you have to use a class that extends Object as the parameter.

Raibaz
  • 9,280
  • 10
  • 44
  • 65
0

the <Integer> specifies the type of the data that the object is going to hold. it is Integer instead of int because the LinkedList is designed to hold an Object and not a primitive. so

Queue<Integer> q = new LinkedList<Integer>();

means that we are creating an Object of LinkedList that holds Integer type objects and we are refering it with a Queue reference variable.

Thirumalai Parthasarathi
  • 4,541
  • 1
  • 25
  • 43
0

what is the <> used with Integer for? And why is it also with the LinkedList object and not in the parameters?

If you have a Parameterized Collection Queue<Integer> than a Raw type Queue it ensures that none of the Objects other than Integer are added in the Collection.

This feature was introduced from Java 1.5

Why is the word Integer used and not int?.

Collection deals with Objects and not primitives.



Consider this example from Effective Java Item 23

// Now a raw collection type - don't do this!
/**
* My stamp collection. Contains only Stamp instances.
*/
private final Collection stamps = ... ;

If you accidentally put a coin into your stamp collection, the erroneous insertion compiles and runs without error:

// Erroneous insertion of coin into stamp collection
stamps.add(new Coin( ... ));

You don’t get an error until you retrieve the coin from the stamp collection:

// Now a raw iterator type - don't do this!
for (Iterator i = stamps.iterator(); i.hasNext(); ) {
Stamp s = (Stamp) i.next(); // Throws ClassCastException
... // Do something with the stamp
}

Example with Parameterized

// Parameterized collection type - typesafe
private final Collection<Stamp> stamps = ... ;

From this declaration the compiler knows that stamps should contain only Stamp instances and guarantees this to be the case, assuming your entire code base is compiled with a compiler from release 1.5 or later and all the code compiles with- out emitting (or suppressing; see Item 24) any warnings. When stamps is declared with a parameterized type, the erroneous insertion generates a compile-time error message that tells you exactly what is wrong:

Test.java:9: add(Stamp) in Collection<Stamp> cannot be applied to (Coin)
stamps.add(new Coin());
JNL
  • 4,683
  • 18
  • 29
0

They are a type of generic (see @JTigger's answer) this means they can be a queue/list of ANY Java object including custom Java objects, this allows you to use the queue/list functions on anything inside of Java without reinventing the wheel.

Example: Say we have the custom Object "planet":

public Class Planet {
    private String name;
    public Planet(String name) { this.name = name; }
    public String getName() { return name; }
}

and we want to put a list of planets inside a queue. We could create said queue, and use the already built add() and remove() methods. If Queue was not a Generic class we would have to build our own add() and remove() functions. So using Generics we can list all the names of the planets in the solar system:

public static void main (String args[]) {
    Queue<Planet> solarSystem = new LinkedList<Planet>();

    solarSystem.add(new Planet("Mercury"));
    solarSystem.add(new Planet("Venus"));
    solarSystem.add(new Planet("Earth"));
    solarSystem.add(new Planet("Mars"));
    solarSystem.add(new Planet("Jupiter"));
    solarSystem.add(new Planet("Saturn"));
    solarSystem.add(new Planet("Uranus"));
    solarSystem.add(new Planet("Neptune"));
    solarSystem.add(new Planet("Pluto")); //For Nostalgia's sake

    for (int i = 0; i < 9; i++) {
        System.out.println(solarSystem.element().getName());
        solarSystem.remove();
    }
}
sparks
  • 736
  • 1
  • 9
  • 29