Talk:Generics in Java

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
WikiProject Java (Rated Stub-class, Low-importance)
WikiProject icon This article is within the scope of WikiProject Java, a collaborative effort to improve the coverage of Java on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
Stub-Class article Stub  This article has been rated as Stub-Class on the project's quality scale.
 Low  This article has been rated as Low-importance on the project's importance scale.
 

Reflection example not correct[edit]

I removed the following text, as it isn't correct:

It is possible to work around this limitation to some extent by using Java's reflection mechanisms. If an instance of class T is available, one can obtain from that object the Class object corresponding to T and use java.lang.reflect.Array.newInstance to create the array.

Let's say I have toArray(List<T> list) with at least one element. I call this using a List&ltNumber&gt containing Integers and Floats. Array.newInstance() using my first element of my list (which an instance of class Number) I end up with an array of type Integer[]. When I try to add a Float to the array, my program will fail with an error.

Now, it is possible if I pass in a Class<T> as in toArray(List<T> list, Class<T> clazz). Calling Array.newInstance(clazz, list.length()) will work just fine. However, I don't think it's worth mentioning this in the actual article. —Matthew0028 07:50, 11 December 2006 (UTC)

This is fair comment but it is actually a different problem to the generics implementation - it is the fact that in Java, the array type A[] is treated as a subclass of type B[] if A is a subtype of B and is implicitly casted, which is incorrect and unsafe. There is no such unsafe type casting with generics, and this also allows a much neater method of obtaining the generic type, as seen in, for example, EnumMap<K extends Enum<K>, V>:

public EnumMap(Class<K> keyType);

EnumMap has to inspect the enum used for the key, so the user has to pass in the class object for the key type K. The generic parameter on the Class object ensures that it is indeed K's class. I think this mechanism should go in the article because I don't know of any ways in which it doesn't do what it's supposed to do. 212.140.169.22 (talk) 09:55, 28 January 2011 (UTC)

Anti-Java bias[edit]

This article only tells what the problems are with Java generics. It doesn't even tell you how to use any of the generic features, like the For-next loop or autoboxing. —The preceding unsigned comment was added by Ed Poor (talkcontribs) 22:30, 7 February 2007 (UTC).

Indeed. It doesn't even define Generics. The first sentence talks about when they were added to the language, and the second goes right into comparison with C++. This article needs work. --King Mir 01:52, 13 February 2007 (UTC)
This article used to be part of the generic programming page (but you know that already), which provided a little more context on the subject. I agree it should at least mention how it can help with type safety (even if only to a degree) and readability (same footnote), and can prevent the need for casts. (Note that foreach and autoboxing don't really require generics, they were in the C# language before it introduced generics.) Perhaps some examples that show the good points would be nice too. - Chip Zero 15:38, 13 February 2007 (UTC)

Anti-Java bias Updated[edit]

Removed the Anti-Java Content, Added viable examples, Corrected Incorrect Example.

This is not a facility to compare Java to other languages; If a comparison is useful, it has every reason to be here.

Please take the time to remove negative/spiteful content when ever possible.

Thank you =)

Oh, the "rules" you refer to are not part of wikipedia policies, except spitefulness, which is forbidden. First of all: please sign your postings with four tildes '~~~~',secondly: it is quite legal to compare Java to other languages here, but there are specific articles for Comparison of C# and Java, Comparison of Java and C++. Specific criticisms without comparisons. could very well be in this article, but there are certain rules: this is not a scribble board, so criticisms must be wide spread outside criticisms, and they should be verified by providing external sources. If there are prominent counterarguments on specific criticisms, it is very desirable those counterarguments are mentioned here too. Wikipedia have no opinion of its own, but it doesn't hesitate to mention important criticisms from outside, since no censorship except the encyclopedic style and layout apply here. Criticisms should be in a section called "criticism", the criticisms should be outside-citable, and the text formulations in this article should be neutral and non-inflamatory. ... said: Rursus (bork²) 15:19, 22 April 2009 (UTC)

Feb 2008 edits[edit]

I tried to improve content of this article. We certainly have to start with relevant to this subject Java language specifications - then to go down to examples. I do not see any reason for autoboxing/unboxing section here - it has nothing to do with generics. Also, nested generics 'explained' here by an example - are simply ugly.--Stagalj (talk) 00:08, 13 February 2008 (UTC)

GCJ[edit]

GCJ 4.3 support all 1.5 features, including generics. I don't know where it should be written, however. And besides, I'm dying for coffee now! ... said: Rursus (bork²) 13:14, 28 April 2009 (UTC)

Reflection?[edit]

“Reflection can also determine the type parameter”. Come again? By what means other than “individual elements may be examined to determine the type they belong to”? --Zahnradzacken (talk) 08:39, 27 October 2010 (UTC)

Java Bytecode representation of generics[edit]

Most of articles on the Internet (including this one) give the reader an impression that generic type information is completely removed from the resulting bytecode when compiling Java source to .class files.

This is wrong - this information is retained on declarations of classes, methods and fields using a bytecode extensibility mechanism called "attribute". Generic type information is saved in the bytecode in the signature attribute.

Erasure of this information takes place during runtime - actual in memory class instances (objects) are unable to hold generic type information so you cannot check them during runtime. However, you can still access generic type information on methods, classes and fields using reflection API:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/GenericDeclaration.html

For detailed explanation, see this article:

http://www.ibm.com/developerworks/java/library/j-cwt02076.html

To cite a fragment: "In this article, I'll show how you can use ASM both to retrieve the raw generics information out of class files and to interpret the generics in a useful manner. Before digging into the ASM details, I'll start off with a look at how generics information is actually encoded into the binary classes."

--Aleksander.adamowski (talk) 19:35, 12 January 2011 (UTC)

Introduction: being straightforward about what this is[edit]

Hi, I just added a short sentence to the introduction to help explain what a generic actually is and how it's often used. I'm no expert so if it's not technically accurate, please do correct me. But please let's keep some sort of helpful, concise summary up there.

I came here when I first heard of generics hoping to find out what they were, but was out of luck because the article was no help. Later, after I learned about them from other sources, I found out it's not really that hard to quickly explain that, say, when you see "BagOfThings<String> bag = new BagOfThings<String>()" it just means they're specifying that the bag will hold strings.

--Qwerty0 (talk) 20:26, 30 April 2011 (UTC)

Hi, why don't you explain why this article was no help?
Thanks for improving the article, but I don't think your sentence actually explains generics (or helps doing so). It only mentions one feature. I don't want to correct you in the first place, as you might come up with much better solution yourself. --Zahnradzacken (talk) 21:32, 3 May 2011 (UTC)

I do not understand the contradiction that required wildcards[edit]

I do not think the explanation of why wild cards are necessary is clear.

List<Integer> ints = new ArrayList<Integer>();
ints.add(2);
List<Number> nums = ints;  //valid if List<Integer> is a subtype of List<Number> according to substitution rule. 
nums.add(3.14);  
Integer x=ints.get(1); // now 3.14 is assigned to an Integer variable!

Isn't nums a separate instance that will change independent of ints? Doesn't nums = ints do a deep copy? I thought the main point (well, one of the main points) of Java was allowing us to ignore memory.

If Java uses the same memory location for nums and ints we should include a link to an article or section explaining how Java manages memory for variables. --Bertrc (talk) 20:51, 19 September 2011 (UTC)

No, Java does not deep copy in the example. There is no pointer arithmetics and no explicit memory allocation (only the second is one aspect of memory management), however Java does have references. If you could not copy reference values, then how could Collections.sort(myList) sort myList?
Although I think that this behaviour does not surprise much, the whole section could benefit from a bit more explanation. For example, the working "solution with wildcards" is missing. --Zahnradzacken (talk) 15:28, 21 September 2011 (UTC)
Zahnradzacken, I meant how Java handles memory, internally. I'm afraid that I still do not understand how the example shows the need for wild cards. After using the the assignment operator to populate nums (or copy constructor to create nums; whatever Java does on that line), isn't nums a separate List instance that will change independent of ints? If so, then why would nums.add(3.14) put 3.14 into the List ints? If nums is the same List object as ints, then we should explain how/why the copy constructor does not create a new List object (or provide a link that explains this). eg:
List<Number> nums = ints;
// Valid if List<Integer> is a subtype of List<Number> according to substitution rule. 
// However, due to how Java handles the assignment operator for templates 
//   nums and ints now refer to the same List instance
nums.add(3.14);  // 3.14 is now added to the List object
Integer x=ints.get(1);
// Now 3.14 is assigned to an Integer variable!  

--Bertrc (talk) 21:05, 6 October 2011 (UTC)

Yes, we may well add a few words explaining why it's a problem. Your second assumption is almost correct: nums points to the same object as ints does, so method invocations (adding, deleting) on nums are resolved to calls on the same list as that of ints. However, a later assignment like nums = Collections.emptyList(); would not empty the list of ints, it only would change the target of where nums points. I do not consider this as (internal) memory handling, but maybe that's just terminology. There's nothing special to constructor assignments, so I'd think about some other article to link to. I just had a look and found Java syntax#Reference types to be quite useful.
I suggest the following lines:
List<Number> nums = ints;
// Illegal according to the typing rules but assumed to be working in order to show why it is illegal
// Assuming it worked, the reference value of the int-list would be assigned to nums.
//   nums and ints now refer to the same List instance
nums.add(3.14);  // 3.14 is now added to the List object
Integer x=ints.get(1);
// Now 3.14 would be assigned to an Integer variable!
--Zahnradzacken (talk) 16:07, 9 October 2011 (UTC)

Wildcards chapter[edit]

In wildcards we find "and writing non-null elements to the list is not allowed". So it's a list with only null elements? Did you mean "and writing null elements to the list is not allowed" 57.66.70.225 (talk) 17:36, 27 January 2012 (UTC)

I think it's a mistake and should be corrected, as of now it's deeply misleading in comparison with examples below this statement. — Preceding unsigned comment added by 212.118.197.121 (talk) 11:35, 21 July 2017 (UTC)

static methods[edit]

The article states "As a result, the type parameter cannot be used in the declaration of static variables or in static methods." but gives an example static method public static <T> Entry<T,T> twice(T value) earlier. So, that must be wrong? --2A01:198:285:0:250:FCFF:FEAD:B479 (talk) 16:44, 6 October 2012 (UTC)