'Linear Search method using generics not working

I am a newbie in java. I tried to make a Linear Search class which can take any type and find it in a list.

package Client.LinearSearch;

    
import java.util.ArrayList;
import java.util.List;

public class LinearSearch<E> {
    public static <E> int Search(ArrayList<E> list, E key) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(key)) {
                return i;
            }
        }
        return 0;
    }
}

But when i tried to search using this method, it shows method cannot be applied to the following types.Linear Search was taken from a list of objects and toSearch is user defined

List<String>nameList=new ArrayList<>();
            for(Employee employee:employeeList){
                nameList.add(employee.getName());
            }
            System.out.println("Enter name: ");
            String toSearch=sc.nextLine();
LinearSearch<String> stringLinearSearch=new LinearSearch<String>();
int index=stringLinearSearch.Search(nameList,toSearch);

![enter image description here][1]

The error message:

java: method Search in class Client.LinearSearch.LinearSearch<E> cannot be applied to given types;
 required: java.util.ArrayList<E>,E
  found:    java.util.List<java.lang.String>,java.lang.String
  reason: cannot infer type-variable(s) E
    (argument mismatch; java.util.List<java.lang.String> cannot be converted to java.util.ArrayList<E>)


Solution 1:[1]

You probably need to loosen up the type for the list parameter. You don't necessarily need an ArrayList; any old List will do. So a method definition like this might help:

public static <E> int Search(List<E> list, E key) {

As a side-note, returning 0 if the element isn't found makes it look like the element actually was found (at index 0). Consider returning something like -1 (the convention for many indexOf functions) instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1