0

Could someone please help me?

I am returning to java after a few years and some things have changed.

I see a lot of these '<>' being used in constructors. Can someone please elaborate? For example:

void method(Object <b>){}

Why is b in between <>

What is the purpose?

Where can I read on new changes to Java since about Java 4/5. Thanks

keshlam
  • 7,931
  • 2
  • 19
  • 33
chokkie
  • 25
  • 2

2 Answers2

1

These are generics. They are parameters that go along with the type. For instance, in Java 4 you'd make a list of things this way:

List stuff = new ArrayList();
stuff.add("watch");
stuff.add("pencil");
stuff.add(5.0f);

With generics, you can specify that it must be a list of something in particular, for instance a list of Strings:

List<String> stuff = new ArrayList<String>();
stuff.add("watch");
stuff.add("pencil");
stuff.add(5.0f); //Doesn't compile. The compiler sees that it's not a string.

Also, since Java 7, you can use the diamond operator at the constructor, like this:

List<String> stuff = new ArrayList<>();

This is so you don't have to type that parameter again (as they can get pretty involved).

Ghostkeeper
  • 2,830
  • 1
  • 15
  • 27
  • Thanks guys, also since found what i need on doc.oracle, Generics looks like fun indeed ;> ! Cheers – chokkie Mar 01 '14 at 16:42
0

The argument you see within the diamond operator (<>) are called generics. Generics were a feature introduced in Java SE1.5. They provide for type safety while using collections of objects as the compiler will now check to see if the elements within the collection belong to the type mentioned within the diamond operator. If not, the compiler will throw an error and the program will not run. Previously, it was possible to have objects of any type be added into a collection and then if an unexpected object type was encountered during run time, then the program would throw an error only then and that was unexpected.

Note that the use of generics is not mandatory but it's just good programming practice to do it.

ucsunil
  • 7,378
  • 1
  • 27
  • 32