we are currently learning Generics in class but I am still confused. I am currently doing an assignment and what my teacher wants me to do is to use the binary search algorithm to search for a circle with a certain radius. I believe I have everything set up but I am confused about how I can pass an array of objects to a generic method. If I can't how else can I get access an array of objects using generics. I hope I am asking this correctly
Here is what I have of course it's not done.
public class Question1
{
public static void main(String[] args)
{
Circle[] b = {new Circle(1),new Circle(2),new Circle(3),new Circle(4),new Circle(5)};
System.out.println(b[0].getR());
run(b,3,0, b.length-1);
}
/**
*
* @param <T>
* @param b
* @param key
* @param low
* @param high
*/
public static <T> Object run(T[] b , T key, int low, int high)
{
int mid = ((low + high)/2);
if(high < low)
{
System.out.print(-1);
}
if(key == b[mid])
{
System.out.println(b[mid]);
}
if(key < b[mid])
{
return run(b,key,low,mid-1);
}
else
{
return run(b,key,mid+1,high);
}
}
}
Thanks, fish
Generics are a way of generalizing code to a variety of types while maintaining type safety. The usual way of introducing someone to generics is to compare the nongeneric List
interface to the generic List<T>
interface. A raw List
can contain any object type and, therefore, is not typesafe. A raw list can contain both your favorite Coin
and Stamp
collection at the same time, which can cause difficult errors when you went to retrieve a Coin
but got a Stamp
instance instead.
A List<Coin>
can contain only contain Coin
instances. The compiler will not allow a Stamp
to be inserted into the list. As long as the program compiles without errors OR warnings, the compiler guarantees that every time you go to get a Coin
out of the list, you will only get Coin
s.
my teacher wants me to do is to use the binary search algorithm to search for a circle with a certain radius.
This assignment does not require a generic method so I'm not sure why you're being asked to write one, unless there are details about the assignment you haven't disclosed.
Your current solution contains one glaring problem: you cannot use the ==
operator to test for value equality among objects. In object comparisons, the ==
operator tests only for identity. This will print false:
System.out.println("my test" == new String("my test"));
The above has two objects with separate identities: the string literal, and the newly created String instance. They both have different identities (even though they have the same value) so the expression evaluates to false. For value comparisons among objects, you need to write an equals()
and a hashCode()
method. This evaluates to true: "my test".equals(new String("my test"));
Notice also that they expression with objects (key < b[mid]) is illegal because the <
operator is not valid for object types.