• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

I don't see an advantage of Generics of Java 5 here!

 
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pradeep mentioned this link in the another thread, but I feel like it would better to start a new thread with a nice subject...

Consider the following in the example of the article in the above link...


For example, with a List of Strings, prior to 1.5 you might write:

List myList = new ArrayList();
myList.add("hello");
myList.add("goodbye");

// myList.add(new Date()); This would compile but cause failures later

Iterator it = myList.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
In 1.5 you can write this as:

List<String> myList = new ArrayList<String>();
myList.add("hello");
myList.add("goodbye");

// myList.add(new Date()); This won't compile!

Iterator<String> it = myList.iterator();
while (it.hasNext()) {
String s = it.next();// Look Ma, no downcast!
System.out.println(s);
}



I don't know that much about the other usage... but here in this example, I found out that the new code with 1.5 has three occurences of <String>: behind List, behind ArrayList and behind Iterator, while in old code, there is only one occurence of (String) to downcast the obtaining object to become a string. It seems like the new 1.5 code fix the type of objects that the list can contain and compiler is able to check it without the help of the application...

Anyone's comments are welcome!!! We are here to taste the flesh of Tiger...
 
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Basically, I am new to Generics in Java.

Ko Ko, Could you breifly explain what is it about? Is it just a common type for displaying all its sub-classes info? Or... ?

Sorry for asking a simple question.

Nick
 
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked.


When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}

Here is the same example modified to use generics:

// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}

When you see the code <Type>, read it as �of Type�; the declaration above reads as �Collection of String c.� The code using generics is clearer and safer. We have eliminated an unsafe cast and a number of extra parentheses. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.

To paraphrase Generics Specification Lead Gilad Bracha, when we declare c to be of type Collection<String>, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time.

While the primary use of generics is collections, there are many other uses. �Holder classes,� such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

<T extends Annotation> T getAnnotation(Class<T> annotationType);
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
Author a = Othello.class.getAnnotation(Author.class);

Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation.
Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.

The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These �checked collection wrappers� are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:

Set<String> s = new HashSet<String>();

with this declaration:
Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);

the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.
You should use generics everywhere you can. The extra effort in generifying code is well worth the gains in clarity and type safety. It is straightforward to use a generic library, but it requires some expertise to write a generic library, or to generify an existing library. There is one caveat: You may not use generics (or any other Tiger features) if you intend to deploy the compiled code on a pre-1.5 virtual machine.

If you are familiar with C++'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit �template metaprogramming.�

There is much more to learn about generics



Reference Website
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ko Ko,

FYI. Pradeep has posted a link to a good article in the thread:
https://coderanch.com/t/374339/java/java/Java-Tiger-New-Features-Reader

You may have a look as well.

Nick
 
Ranch Hand
Posts: 8944
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

seems like the new 1.5 code fix the type of objects that the list can contain and compiler is able to check it without the help of the application...



That is right. Generic will provide you the runtime type safety which will avoid lot of errors. You will be sure that the ArrayList contains only String and you will be able to code without any ClassCastException.

Prior to tiger you would be expected to cast every time you retrive objects from collections. With the power of tiger you dont need to cast which is lot useful.
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks somkiat.

I am already reading the PDF mentioned by Pradeep.

In such sense, seems Generics only work for Collection, rite?

Nick
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Nicholas Cheung:
Basically, I am new to Generics in Java.

Ko Ko, Could you breifly explain what is it about? Is it just a common type for displaying all its sub-classes info? Or... ?



Generics kind of generalization of the various types... If you ever tried C++'s template before, it's similar to C++'s template... We don't need to specify the types of the class or primitive in the code; and the application can run it smoothly....

For instance, float add(float a, float b ) function works very similar way as int add(int a, int b), double add(double a, double b), long add(long a, long b) and so on... C++'s template does not need to code all overloaded methods like this and it can work amazingly...

I used to play around with C/C++ before and moreover I am currently studying all the major programming langauges in master course as well... That's one of the reasons why I have to learn more things about programming languages' features in details...

I would have to be sorry, if my explanation is not good enough for you to understand fully about the generics...
 
Pradeep bhatt
Ranch Hand
Posts: 8944
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I would have to be sorry, if my explanation is not good enough for you to understand fully about the generics



Dont worry. Tutorial will help him.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Nicholas Cheung:
Ko Ko,

FYI. Pradeep has posted a link to a good article in the thread:
https://coderanch.com/t/374339/java/java/Java-Tiger-New-Features-Reader

You may have a look as well.

Nick



I don't see any link to the article in that thread, Nick... Could you paste the link here? Thanks..
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Nicholas Cheung:
Thanks somkiat.

I am already reading the PDF mentioned by Pradeep.

In such sense, seems Generics only work for Collection, rite?

Nick



can use in Collection Framework , not Only Collection.

 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ko Ko.

Nick
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Pradeep Bhat:


That is right. Generic will provide you the runtime type safety which will avoid lot of errors. You will be sure that the ArrayList contains only String and you will be able to code without any ClassCastException.

Prior to tiger you would be expected to cast every time you retrive objects from collections. With the power of tiger you dont need to cast which is lot useful.



Thanks Pradeep for ur great comment on it... I am gradually getting the idea of generics feature of Tiger...

Mmm, Tiger's flesh taste good...
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In fact, that's why SUN decides to call it Java v5.0, or J5SE, as this release really provides lots of changes that the prior releases did not.

Nick
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Pradeep Bhat:
(...)
Prior to tiger you would be expected to cast every time you retrive objects from collections. With the power of tiger you dont need to cast which is lot useful.



No - - don't agree.
Prior to tiger you wrote your own typesafe collection (like this):

to have a typesafe collection and avoid permanent casting.

Of course, every serious programer made a small Template-class, which could be populated by the needed type:
generate_javalist Foo
This templates can now be thrown away.
 
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The reason I'm a bit apprehensive about generics is that they're magic. When I started learning java, everything seemed like magic, I just copied code from somewhere and it did what the book said it should. But then you begin to realize, there are a VERY limited 'rules' in java. When you say System.whatever, you're not just typing a magic keyword, you're just dealing with static members of a class. Back in turtle graphics when I said pen.move(19), it's not code word, it's just a method on an object. All the rules are right there. But angle brackets?! <String>? that doesn't resolve to the basic rules. Knowing how objects work is not enough to get through generics. And don't ever try to tell me it removes clutter. Type casts may be phyisically clutter, but they obey the rules, they make sense, and the mental clutter is 0. The object rules all make sense, and accomplish everything you need to. Magic scares me. There's the entire, well-worked out object system, and then they have to go and add an extra bell/wistle that doesn't fit with the rest, doesn't meld.

I don't like change.
 
Author
Posts: 253
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will add just a couple of quick points to the preceding disucssion.

As I have been saying in other posts: Generics change Java! First,
generics add type-safety. Prior to generics, all "generic" code had to operate on objects of type Object. This made runtime type-mismatches possible. It also prevented the compiler from being able to ensure that a collection, for example, contained only the types of objects that you really entended for it to contain. With generics, the compiler can ensure type compatibility, and prevent runtime errors.

Second, generics also enable you to more effectively re-use your code because the type of data operated upon by a generic class, method, or object is passed to it as a type parameter. This is why generic classes are called parameterized types.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Joseph George:
The reason I'm a bit apprehensive about generics is that they're magic. When I started learning java, everything seemed like magic, I just copied code from somewhere and it did what the book said it should. But then you begin to realize, there are a VERY limited 'rules' in java. When you say System.whatever, you're not just typing a magic keyword, you're just dealing with static members of a class. Back in turtle graphics when I said pen.move(19), it's not code word, it's just a method on an object. All the rules are right there. But angle brackets?! <String>? that doesn't resolve to the basic rules. Knowing how objects work is not enough to get through generics. And don't ever try to tell me it removes clutter. Type casts may be phyisically clutter, but they obey the rules, they make sense, and the mental clutter is 0. The object rules all make sense, and accomplish everything you need to. Magic scares me. There's the entire, well-worked out object system, and then they have to go and add an extra bell/wistle that doesn't fit with the rest, doesn't meld.

I don't like change.



Perhaps it seems to violate the rules you are used to as a Java programmer. Obviously Sun had to invent new rules in order to allow such a mechanism. I'm certain that if you care to learn these new rules, you will see that generics follow them quite well.

Also, as already mentioned, there is a precedent in other languages, namely C++. I agree that generics seem quite similar to C++ templates, and I welcome the addition to the Java language.
 
blacksmith
Posts: 1332
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Layne Lund:

Also, as already mentioned, there is a precedent in other languages, namely C++. I agree that generics seem quite similar to C++ templates, and I welcome the addition to the Java language.

I think it should be noted that Java generics are much simpler and safer than C++ templates. In fact, the ANSI C++ template specification is so complex that, as of the last time I checked, no compiler had actually implemented it fully on any platform.

Like Joseph George, I don't like change. Sometimes change is a sufficient improvement to justify the pain and effort of getting used to it, though - of, as Joseph George puts it, learning it well enough that it doesn't seem like "magic" any more.

Is this the case for generics? When I first used Java, my biggest complaint was lack of generics, as I was coming from a C++ background where I used templates regularly. But then I got used to the Java way of doing things. I've gotten bitten by a ClassCastException from improper use of a collection exactly once in the past five years - though admittedly it was a particularly painful bug to find and fix (took a full day). Writing type safe wrappers around all my collections for that whole period would have taken a lot more than one day - probably dozens of days, I use collections a lot - so with Java 1.4, it was more efficient for me to do the casting. Typing the parameter in for all those collections would probably have totalled to less than a day - actually it would have saved me time relative to all the casts I had to type in - so that's a win for me. But that's for a person who is used to the <parameter> syntax from C++.

For people who don't like the new syntax, you can always use the old casting method. I think the new way is worth learning, though - although I have to admit I think the angle brackets are ugly, in C++ as well as Java.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
although I have to admit I think the angle brackets are ugly, in C++ as well as Java.

Especially if you need a 2D array:

*shudders*

In fact, will generics support this kind of nesting as C++ templates do?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Warren Dew:
Java generics are much simpler and safer than C++ templates
I would agree that they seem much simpler, from what I've read of them. However, I don't see that they are "safer." I'm curious what motivates this claim? Can you give an example?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Layne Lund:

I'm certain that if you care to learn these new rules, you will see that generics follow them quite well.



I sort of feel like if you are going to have bells and wistles beyond your set of rules, go ahead and have bells and wistles. But prior to generics, there
were no bells or wistles. just having a single bell/wistle sticks out like a sore thumb.
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


For example, with a List of Strings, prior to 1.5 you might write:

List myList = new ArrayList();
myList.add("hello");
myList.add("goodbye");

// myList.add(new Date()); This would compile but cause failures later

Iterator it = myList.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}



I submit that this exception originates not from shortcomings in Java, but from simple poor programming. Keep track of your lists, and this will NEVER be a problem. I find this even easier when you don't name your list 'myList,' but something like 'strings.' Then, if you try to add a Date to a list called 'strings,' a little bell should ding in your head that something might not be right.

String s = it.next(); // Look Ma, no downcast!



Are type casts really sooo durn cumbersome?
 
Herb Schildt
Author
Posts: 253
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To all:

There is little more that I can add to the excellent comments in this thread, with this one exception: Generics are here to stay!

Remember, the compiler will generate a warning if you don't use them when when working with a collection, or any other generic type in the API. There is a reason for this: generics enforce compile-time type-safety, as several of the posts point out. Frankly, given that you can have compile-time type-safety, it is impossible to justify not using it. Imagine trying to tell your client that his application failed because you didn't bother using the compile-type type checks now available in Java!
[ August 24, 2004: Message edited by: Herb Schildt ]
 
Pradeep bhatt
Ranch Hand
Posts: 8944
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Stefan Wagner:

to have a typesafe collection and avoid permanent casting.

Of course, every serious programer made a small Template-class, which could be populated by the needed type:
generate_javalist Foo
This templates can now be thrown away.



Yes, every programmer could write the above template but when there are lot of Collection classes used it in an application it becomes difficult to wtrite these classes. Of course you could use some code generation tool.
 
Pradeep bhatt
Ranch Hand
Posts: 8944
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Are type casts really sooo durn cumbersome?



No they are not atleast for me. The real benefit is that there is no chance of ClassCastException. Isn't that good? :roll:
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Herb Schildt:
Prior to generics, all "generic" code had to operate on objects of type Object. This made runtime type-mismatches possible. It also prevented the compiler from being able to ensure that a collection, for example, contained only the types of objects that you really entended for it to contain. With generics, the compiler can ensure type compatibility, and prevent runtime errors.



Then can we conclude that the new generics applies compile-time type checking, while the previous Object-type-based generic code applies runtime type checking? :roll:

If so, we can see clearly that the new generics is more effective and type-safety than the previous Object-type-based generic code approach...
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In fact, moving things to the compiler and JVM do help reducing the human coding errors, but does Generics really solve all stuffs of problems?

Any potential threads?

Nick
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
does Generics really solve all stuffs of problems?

Ummm... no. Of course not. Why would this even be a question? No one has ever claimed that generics would solve all problems. Or even all programming problems.
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the term *those problems*, I am refering to the casting issues.

Any issues that Generics has not been addressed?

Nick
 
Warren Dew
blacksmith
Posts: 1332
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Layne Lund:

I would agree that they seem much simpler, from what I've read of them. However, I don't see that they are "safer." I'm curious what motivates this claim? Can you give an example?

I think that writing C++ templates is more bug prone than writing Java generics will be. At least I'm hoping that's true. Typically, writing a C++ template involves first writing an nontemplate class and testing it, then converting it to a template and testing that, and finally writing generic pointer (void *) implementations for any parameterized types that are pointer types in order to avoid code bloat. Properly written Java generics, if I understand them correctly, ought to be writable directly on the superclass of the types on which the generic can be parameterized, which will skip a couple of bug prone steps. Java gets this advantage from the fact that they've accepted a couple of limitations: generics can only be parameterized on subclasses of some root class, and generics can't be parameterized on primitive types. Put another way, Java generics have the advantage of operating in a world where each object carries type information; C++ templates have to operate on arbitrary blocks of binary data which may or may not be the classes they expect, which makes them more bug prone.

In addition, in most C++ implementations, you have to help out the compiler on template instantiation. Often this includes putting implementations into header files, which means the code which uses templates can develop hidden dependencies on the implementation of the generics. You can also get severe code bloat if the same template gets instantiated the same way in multiple linkage units, and subtle bugs if not all the linkage units are up to date. I think Java can avoid this because their generics are limited to operating on objects that carry type information, not primitive types or C++ style objects that are essentially binary data structures carrying no type information.

Java generics do give up a certain amount of power for this safety, of course.
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Java generics do give up a certain amount of power for this safety, of course.



Safety in compile time ...


I think, this feature is good for programmer/developer in coding phase and solve ClassCastException Problem.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Pradeep Bhat:


No they are not atleast for me. The real benefit is that there is no chance of ClassCastException. Isn't that good? :roll:



No for me as well... But I won't need to worry about the chance that mized-type Objects might be in the collection at least...
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But honestly, the developers should always make sure the type of the target objects, before accessing them, isnt it?

Nick
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Nicholas Cheung:
But honestly, the developers should always make sure the type of the target objects, before accessing them, isnt it?

Nick



But using Generics, we do not need to make sure about that anymore, if we ensure the type of the objects to be put since the beginning... How robust it is!!!
 
Pradeep bhatt
Ranch Hand
Posts: 8944
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

But honestly, the developers should always make sure the type of the target objects, before accessing them, isnt it?



It would have been great If developers could code properly but human beings make mistake. So leave this job to compiler and code without worry.
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Pradeep Bhat:


It would have been great If developers could code properly but human beings make mistake. So leave this job to compiler and code without worry.



Not to mention the fact that you might provide a class that takes a collection of String objects and Jo Henry in the other cubicle decides to use your class, he might forget or not know it only takes Strings. So he will find out at compile time rather than runtime and this will save some headaches.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gregg Bolinger:


Not to mention the fact that you might provide a class that takes a collection of String objects and Jo Henry in the other cubicle decides to use your class, he might forget or not know it only takes Strings. So he will find out at compile time rather than runtime and this will save some headaches.



Simple, but nice example to show the advantage of Generics... Thanks for that, Gregg...
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In answer to the multi-dimensioned generics question...

ArrayList<ArrayList<String> >

I would guess that that would work, as is, but if it wouldn't, you could always create a wrapper object...

ArrayList<ArrayListOfStrings> and define the class ArrayListOfStrings as a small wrapper around ArrayList<String>.

However, like I said, I would guess that this would just work. Can someone confirm?
 
author
Posts: 799
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Creating parameterized types can make for some interesting method signatures that will never fit on a single line. This example is from Collections.java:



Explanation (I hope I get this right): binarySearch searches against a list bound to any type T, as long as T is a subclass of any object that implements the Comparable interface, which in turn must be bound to T or a supertype of T. The key must implement the Comparable interface with the same restrictions.

There's also a hook for backward compatibility: T's declaration includes an upper bound of Object so that the method signature for binarySearch equates to the same as in earlier versions of Java.

Fun stuff.

-J-
 
pie sneak
Posts: 4727
Mac VI Editor Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


I submit that this exception originates not from shortcomings in Java, but from simple poor programming. Keep track of your lists, and this will NEVER be a problem.



Applications can change as you write them. If you are using a list of Strings and then come to find out that you need to use a new bean class instead of String, it CAN be cumbersome. It can be a lot to keep track of.

If this list was accessed in twenty+ places in your app, the compiler does not tell you about them. It does not care, as they are cast to String.

With generics, the compiler now prevents the developer from coding ClassCastExceptions... and we don't have to extend the collections classes just to provide such functionality.
 
That's a very big dog. I think I want to go home now and hug this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic