Cannot find symbol - class T

16,306

Solution 1

Method signature for generic method is as follows

 public static <T> T[] addToArray(T item, T... items){
      T[] array;
      int array_size = 1;

      if(items !=null){ array_size = items.length+1; }

      array = java.util.Arrays.copyOf(items, array_size);
      array[array_size-1] = item;

      return array;
    }

Solution 2

You need to declare the type parameter before the return type of the method:

public static <T> T[] addToArray(T item, T... items)

Reference:

Solution 3

To make a generic method, you need to declare it as taking a generic type parameter:

public static <T> T[] addToArray(...)
Share:
16,306
Nir
Author by

Nir

Updated on September 14, 2022

Comments

  • Nir
    Nir over 1 year

    I've this function;

      public static T[] addToArray(T item, T... items){
        T[] array;
        int array_size = 1;
    
        if(items !=null){ array_size = items.length+1; }
    
        array = java.util.Arrays.copyOf(items, array_size);
        array[array_size-1] = item;
    
        return array;
      }
    

    And I get this error cannot find symbol symbol: class T. The idea is to make this method generic. I never worked with generics so I'm guessing I miss some reference?

  • maba
    maba over 10 years
    I think it's better to link to the official tutorial instead: docs.oracle.com/javase/tutorial/extra/generics/methods.html
  • Rohit Jain
    Rohit Jain over 10 years
    @maba. Well, I've linked the best reference I know about generics. Anyways, official one is also worth reading.
  • Ermiya Eskandary
    Ermiya Eskandary over 2 years
    Why though? Just spent 15 minutes trying to figure out how to do this coming from a C# background - if the compiler can see T, why do we need the type parameter...