-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerics.java
66 lines (50 loc) · 1.93 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
package technicals;
import java.io.*;
import java.util.*;
//Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces.
//Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity.
class Printer
{
<T> void myprinter(T arr[]) //T is used as a generic symbol T identifies which kind of array did we passed
{
for(T e:arr)
{
System.out.println(e);
}
}
<T> void myprinter(ArrayList<T>arr) //method overloaded.
{
System.out.println(arr);
}
}
public class GENERICS
{
public static void main(String[] args) throws IOException
{
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter the length of the array");
int n= Integer.parseInt(inp.readLine()); //buffered reader for integer input
Integer [] num = {1,2,3};
String [] words = new String[n];
System.out.println("Enter the words");
for(int i=0;i<n;i++)
{
words[i]=inp.readLine();
}
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the numbers");
for(int i=0;i<n;i++)
{
list.add(Integer.parseInt(inp.readLine()));
}
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list2, words); //copying all the elements of array into Arraylist.
Printer pp = new Printer();
pp.myprinter(words);
System.out.println("Numbers from predefined array");
pp.myprinter(num);
System.out.println("From list");
pp.myprinter(list);
pp.myprinter(list2);
}
}