Typical Typical Java Type Type

Viewing libraries through Guava I saw this strange signature in the readLines method from the Files class:

public static <T> T readLines(File file,
                          Charset charset,
                          LineProcessor<T> callback)

I know a little about generics in java, but it puzzled me.

What does double t mean here? And why the first in angle brackets?

UPDATE : Thanks for the answers. I still don't understand why I should use T inside brackets. Why, for example, it cannot be simple:

 public static <> T readLines()

or

 pulibc static <K> T readLines()

Or does the java syntax determine that ONLY the letter should be used?

Now this is even weirder:

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {

how can a method have a return type and be invalid?

+5
source share
5 answers

, T . , , :

 public static <> T readLines()

 public static <K> T readLines()

java , ?

<T> <K> - . <K> T, T , , class T. , , T .

:

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {

?

; <T> " ", . , , T . void.

+3

- T . , :

public <T> T foo(T[] bar)

, . String, String . Sun " " .

: , <T> : , T . , , :

static <T> void fromArrayToCollection(T[] a, Collection<T> c)

, fromArrayToCollection , . , String[] Collection<String>, Integer[] Collection<Integer>, String[] a Collection<Integer>. , T, .

+9

T , . T - . T . T .

T , LineProcessor <T> .

+7

, , readLines generics.

  • <T> ,
  • .

, , .

class Generic <T> 
{
public static T readLines(File file,
                          Charset charset,
                          LineProcessor<T> callback)
}

, , .

:

public static <ElementType,ListType extends List<ElementType>> ListType add(ListType list,ElementType elem)
{
   list.add(elem);
   return list;
}
ArrayList<String> = add(add(new ArrayList<String>(),"Hello"),"World");

.
.
, T .

  • ElementType - , ( / )
  • ListType - , / List ElementType.

:

  • ElementType = String
  • ListType = ArrayList

public static ArrayList<String> add(ArrayList<String> list, String elem)

: -)

+3

.

Actually there are three Ts, the third one LineProcessor<T>indicates T when you use the method.

0
source

All Articles