<\/span><\/h2>\n\n\n\nGeneric methods are a very efficient way to handle multiple datatypes using a single method. This problem will test your knowledge on Java Generic methods.<\/p>\n\n\n\n
Let’s say you have an integer array and a string array. You have to write a single method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.<\/p>\n\n\n\n
You are given code in the editor. Complete the code so that it prints the following lines:<\/p>\n\n\n\n
1\n 2\n 3\n Hello\n World<\/code><\/pre>\n\n\n\nDo not use method overloading because your answer will not be accepted.<\/p>\n\n\n\n
<\/span>Solution –<\/strong> Java Generics<\/strong><\/span><\/h2>\n\n\n\nimport java.io.IOException;\nimport java.lang.reflect.Method;\n\nclass Printer\n{\n \/\/Write your code here\n \n public <T> void printArray(T[] elements){\n for (T element : elements){\n System.out.println(element);\n \n }\n }\n \n}\n\npublic class Solution {\n\n\n public static void main( String args[] ) {\n Printer myPrinter = new Printer();\n Integer[] intArray = { 1, 2, 3 };\n String[] stringArray = {\"Hello\", \"World\"};\n myPrinter.printArray(intArray);\n myPrinter.printArray(stringArray);\n int count = 0;\n\n for (Method method : Printer.class.getDeclaredMethods()) {\n String name = method.getName();\n\n if(name.equals(\"printArray\"))\n count++;\n }\n\n if(count > 1)System.out.println(\"Method overloading is not allowed!\");\n \n }\n}<\/pre>\n\n\n\n