简体   繁体   中英

How do i differ primitive data types from generics in Java?

I'm starting to learn Java and i've got a question.

Primitive data types are created as any objects in Java? I mean, somewhere in a deep, there is a class which is called Int. Generics are the templates kind of like for creating new data types, right? In terms of convention, we have to put them in angle brackets, like <HugeInteger> .

Primitive types (like int, double, float) are not Objects. They are primitives and can sometimes be quite annoying and cannot be used as Generics.

For generics you need Objects. That would be Integer, Double, Float and the like.

By the way, there is no class called Int (with an upper case i) unless you declared it.

Generics aren't meant to represent primitives. They're meant to represent objects (as the generic types all extend Object implicitly).

You can use the wrapper variants of the primitive class you want instead to achieve the same effect.

 DDHGeneric<Integer, Integer, Integer, Integer> t = new DDHGeneric<>();

Here is a brief excerpt from Why Use Generics? , found in the Java Trails:

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.

Credit goes to @ Makoto

For learning more, you can go through this tutorial: Restrictions on Generics

Not really, regular objects are created with use of new() keyword:

Object myObject = new Object();
Integer myInt = new Integer(5);

Calling new() allocates some memory space on so called heap, in order to store a newly defined instance. Everytime you call your instance, JVM looks at memory address where it was stored.

On the other hand primitives are registered in memory during the compile time. Lets assume you have a line:

int i = 5;

While compliling your program, JVM (java virtual machine) creates a spot for i variable, remembers where that spot is, and everywhere where it wants to use the value of i it takes it from that place. If other primitive has the same value (eg int y = 5 ), it is assigned to the same place in memory. It means, that primitives are stored by its value.

Hello and welcome to Stack Overflow. First of all, there aren't classes for primitive types. Well, there are Integer and Float , and so on, but these are wrapper classes . They just contain a int (Or float ) variable. Generics are useful for stuff where, for instance, you had a class called Couple , which contains two objects, but you don't know what. They let you tell the class that when you instantiate it instead of pre-defining it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM