I just got a homework assignment, and it’s just creating a linear search algorithm in java. However, I also want to make this code work with any data type like Strings, ints, doubles, etc and different kinds of containers like arrays, hashsets, lists, and collections, so I won’t have to waste so a lot of extra lines to overload the method. Here’s the current code.
public class Search
{
public int linear (Object[] contents, Object query)
{
for (int index = 0; index < contents.length; ++index)
{
if (query.equals(contents[index]))
{
return index;
}
}
return -1;
}
}
However, in my other class, for testing, I have an int array and an int to search for. I get an error that says “The method linear(Object[], Object) in the type Search is not applicable for the arguments (int[], int)”
int is not an object, it’s a primitive. you may user Integer[]. Better yet, you should use generics. You may also want to use list instead of array (just a thought): I show both below.