Java generics – a comparable interface
•
Java
In the following code, the comparable interface is used to ensure that X and y should have the same reference type, but when V is extended to t, V should be the same as the type of T or the subclass of T. what is the focus of using the comparable interface
public class Generics_13 { static <T extends Comparable<T>,V extends T> boolean isIn(T x,V[] y) { for(int i = 0;i < y.length;i++) if(x.equals(y[i])) return true; return false; } public static void main(String[] args) { Integer nums[] = {10,20,30}; if(isIn(10,nums)) System.out.println("10 belongs to the array"); if(!isIn(60,nums)) System.out.println("70 doesnt belong to the array"); String arr[] = {"Neeraj","Parth","Ritum"}; if(!isIn("abc",arr)) System.out.println("abc doesnt belongs to the array"); /*if(isIn("String",nums)) // illegal System.out.println("This wont compile"); */ } }
Solution
The current use of generics is not really meaningful because comparable methods have not been used, which means that you can simply remove the extensions declaration
In addition, type V is not used because you can simply replace it with t without breaking your logic Therefore, the final results are as follows:
public class Generics_13 { static <T> boolean isIn(T x,T[] y) { for(int i = 0;i < y.length;i++) if(x.equals(y[i])) return true; return false; } // main() etc follow here }
But now we have the stream API in java-8. You can use the following code snippet to achieve the same purpose:
static <T> boolean isIn(T x,T[] y) { return Arrays.stream(y).anyMatch(i -> i.equals(x)); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码