I'm new to Java but not to programming (I normally code in Ruby). One thing I've seen in Java code examples is the use of <> instead of () to pass params to an object. Below is a code example (taken from a Google Web Toolkit tutorial):
public void onValueChange(ValueChangeEvent<String> event) {
String token = event.getValue();
// depending on the value of the token, do whatever you need
...
}
Does it have to do with casting or is it something else? Can someone explain to me what this signifies or is used for? Thanks!
That's a type parameter for a generic class. Basically, a ValueChangeEvent<String>
represents an event that notified listeners that a value has changed, and in this case the value is of type String
.
It's easier to understand with the standard example in the collections framework:
A List<String>
is a List
that contains String
objects. The advantage over just using the "raw type" List
is that the compiler will refuse code that puts anything except String
objects into a List<String>
, and allow objects retrieved from it to be used as String
without casting.
Basically, generics allow cleaner code and improve the overall type safety of Java code by making it unnecessary in many cases to work with the Object
type and cast values from it.
It is called generics, or generic parameters. They allow a method or object to operate on multiple types of data while maintaining type safety. One common use is to specify what the type of the objects stored in a collection is.
See the wikipedia article on the subject for more information.
The use of angle brackets usually signify generic programming methods, which is a style of programming where types are not declared initially, making code much more re-usable.
For example:
// Declare the generic class
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
Reese has the right answer. Here are some links for you:
http://download.oracle.com/javase/1.5.0/docs/guide/language/generics.html
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (PDF)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With