Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method java 6 <T> before return type

Tags:

java

generics

What is the difference between:

public <T> void createArray(T sample){
    ArrayList<T> list = new ArrayList<T>();
    list.add(sample);
}

and

public void createArray(T sample){
    ArrayList<T> list = new ArrayList<T>();
    list.add(sample);
}

I read that the method signature for using types should have <T> before the return type but how come I am still able to create the method without the <T>? What is the implication if I do or do not put it?

like image 577
mel3kings Avatar asked Nov 17 '15 10:11

mel3kings


People also ask

How do I return a generic class type in Java?

(Yes, this is legal code; see Java Generics: Generic type defined as return type only.) The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.

Why do we use T in generics?

In other words, the T is an actual part of the syntax for Generics and it means that the paramter for the Class can be of variable type? <T> is the generic type. Maybe read the official tutorial. Yes, the angle-brackets with one (or more) types is the syntax for generics.

What is T type Java?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

What is the difference between T and E in Java generics?

Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>


2 Answers

In the second method, the type parameter would be typically defined in the class declaration to which the method belongs:

class MyClass<T> {
   public void createArray(T sample){
      ArrayList<T> list = new ArrayList<T>();
      list.add(sample);
   }
   ...
}

So the second method belongs to a generic type. The first method is a generic method because it defines its own type parameter.

like image 171
M A Avatar answered Oct 16 '22 10:10

M A


In the first case, the generic parameter T is defined for the method. Other methods may have a different T.

In the second case, the generic parameter T is defined for the class or interface. All methods within that class or interface must have the same T.

Defining a class-wide generic allows you to enforce the same type parameter on many methods. You can also have fields of the generic type. See ArrayList<t> for an example.

like image 13
sdgfsdh Avatar answered Oct 16 '22 10:10

sdgfsdh