-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generics.java
66 lines (53 loc) · 1.44 KB
/
Generics.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Generic methods are a very efficient way to handle multiple datatypes using a single method. This problem will test your knowledge on Java Generic methods.
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.
You are given code in the editor. Complete the code so that it prints the following lines:
1
2
3
Hello
World
*/
import java.io.IOException;
import java.lang.reflect.Method;
class Printer
{
//Write your code here
public static<E> void printArray(E[] elements)
{
for(E ele:elements)
{
System.out.println(ele);
}
}
}
public class Solution {
public static void main( String args[] ) {
Printer myPrinter = new Printer();
Integer[] intArray = { 1, 2, 3 };
String[] stringArray = {"Hello", "World"};
myPrinter.printArray(intArray);
myPrinter.printArray(stringArray);
int count = 0;
for (Method method : Printer.class.getDeclaredMethods()) {
String name = method.getName();
if(name.equals("printArray"))
count++;
}
if(count > 1)System.out.println("Method overloading is not allowed!");
}
}
/*
Your Output (stdout)
1
2
3
Hello
World
Expected Output
1
2
3
Hello
World
*/