• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why generics won't work with primitive data types?  RSS feed

 
bhanuchandra guntrotu
Greenhorn
Posts: 1
Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generic classes can't take primitive data type. Why?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Simply, that is how they were designed. In Java, Generics are only for Objects. In terms of implementation, they are actually type erased to the Object class when they are compiled.

Henry
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

When generics was introduced in Java5, they also introduced boxing conversion. So you can declare a type parametrised to ose of the eight primitive wrapper types and add primitives:-Remember that an int is not an Object.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've understood that Java 10 may allow primitives to be used for generic types, but don't be surprised if that gets postponed to an even later version.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a project named "Project Valhalla" which people at Oracle are working on, which is about investigating a number of possible new features for a future Java version, such as value types and generic specialization. One of the features we will get when this is added is the possibility to use primitive types as type arguments, without the boxing / unboxing overhead.

I've written two blog posts about this: Value Types and Generic Specialization.
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i can't help this. java is getting better, but I am impressed with scala and others. in scala there are no primitives. numbers and Booleans are just like classes. you can say 5.+(2). the plus sign is a method of the number class. you can also pass functions(methods)around.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!