-2

I would like to try to create a generic method that takes an array, the length of the array, and an element that returns the position of the element in the array. I'm new to Java and I'm trying to learn Generics.

I can't seem to get the position of the element, and I don't even know if I'm doing this right, any advice would be great.

public class GenericsProj {

    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3, 4};
        String[] stringArray = {"one", "two", "three", "four"};

        routineArray(intArray, intArray.length, 4);
        routineArray(stringArray, stringArray.length, "four");
    }


    public static <T> void routineArray(T[] array, T length, T element) {
        System.out.println("Inside the array: " + Arrays.toString(array));
        
        for (int i = 0; i < array.length; i++) {
            if (array[i] == element) {
                pos = array[i];
                System.out.println(pos);
            }
        }
    }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Nicole F
  • 11
  • 4
  • 2
    You should not make the `length` of type `T`, the length is ALWAYS an `int`, same goes for the position, will always be an `int`. – luk2302 Nov 05 '20 at 15:06
  • 1
    And apart from that you be encountering https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – luk2302 Nov 05 '20 at 15:07
  • 1
    You don't need the `length` parameter or `pos` anyways (and you haven't declared `pos`). If you want the index of the element, print `i` instead of `array[i]`. Also, use `.equals` instead of `==` when comparing strings and other objects. – user Nov 05 '20 at 15:10
  • omg, you all are life savers, thank you!! now I'm going to try to create a greater than method that will compare two objects, AHH. – Nicole F Nov 05 '20 at 15:23

1 Answers1

-1

Now routineArray prints for each occurrence the element from your input if the element is in the array list, if you want return the position of the element you need to do pos = i instead of pos = array[i]. In this case, you can change the return type of the method from T to int.