I am currently studying Java and have recently been stumped by angle brackets(<>). What exactly do they mean?
public class Pool{
public inter
It's really simple. It's a new feature introduced in J2SE 5. Specifying angular brackets after the class name means you are creating a temporary data type which can hold any type of data.
Example:
class A{
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
public class generics {
static void print(E[] elements){
for(E element:elements){
System.out.println(element);
}
}
public static void main(String[] args) {
A obj=new A();
A obj1=new A();
obj.add("hello");
obj1.add(6);
System.out.println(obj.get());
System.out.println(obj1.get());
Integer[] arr={1,3,5,7};
print(arr);
}
}
Instead of
, you can actually write anything and it will work the same way. Try writing
in place of
.
This is just for convenience:
is referred to as any type
as element type
as number type
as value
as keyBut you can name it anything you want, it doesn't really matter.
Moreover, Integer
, String
, Boolean
etc are wrapper classes of Java which help in checking of types during compilation. For example, in the above code, obj
is of type String
, so you can't add any other type to it (try obj.add(1)
, it will cast an error). Similarly, obj1
is of the Integer
type, you can't add any other type to it (try obj1.add("hello")
, error will be there).