Angle Bracket <> in Java with Examples
Last Updated :
18 Apr, 2022
Angle Bracket in Java is used to define Generics. It means that the angle bracket takes a generic type, say T, in the definition and any class as a parameter during the calling. The idea is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.
Example:
<T> // of type T
<Integer> // of type Integer
<String> // of type String
<MyClass> // of type MyClass
.
.
How to use angle bracket with Class?:
We use angle brackets ‘<>’ to specify parameter types in generic class creation. To create objects of a generic class, we use the following syntax:
// To create an instance of generic class
BaseType obj = new BaseType ()
Note: In Parameter type,
we can not use primitives like
'int', 'char' or 'double'.
class Test<T> {
T obj;
Test(T obj)
{
this .obj = obj;
}
public T getObject()
{
return this .obj;
}
}
class Main {
public static void main(String[] args)
{
Test<Integer> iObj
= new Test<Integer>( 15 );
System.out.println(iObj.getObject());
Test<String> sObj
= new Test<String>( "GeeksForGeeks" );
System.out.println(sObj.getObject());
}
}
|
How to use angle bracket with Function?:
We use angle brackets ” to specify parameter types in the generic function definition. Then to call the function, we just pass the expecter type as a parameter. We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method, the compiler handles each method.
// To create a generic function
public static void func(T a, T b){}
Note: In Parameter type,
we can not use primitives like
'int', 'char' or 'double'.
class Test {
static <T> void genericDisplay(T element)
{
System.out.println(
element
.getClass()
.getName()
+ " = " + element);
}
public static void main(String[] args)
{
genericDisplay( 11 );
genericDisplay( "GeeksForGeeks" );
genericDisplay( 1.0 );
}
}
|
Output:
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
Share your thoughts in the comments
Please Login to comment...