Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Object<String> signify in Java?

Tags:

java

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!

like image 471
Nicholas C Avatar asked Nov 27 '10 21:11

Nicholas C


4 Answers

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.

like image 65
Michael Borgwardt Avatar answered Sep 21 '22 07:09

Michael Borgwardt


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.

like image 24
Reese Moore Avatar answered Sep 21 '22 07:09

Reese Moore


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>();
    }
}
like image 43
Greg Avatar answered Sep 23 '22 07:09

Greg


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)

like image 24
mchang Avatar answered Sep 19 '22 07:09

mchang