-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericsInterface.java
More file actions
44 lines (40 loc) · 1.3 KB
/
Copy pathGenericsInterface.java
File metadata and controls
44 lines (40 loc) · 1.3 KB
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
// A generic interface example.
// A generic containment interface.
// This interface implies that an implementing class contains one or more values.
interface Containment<T> {
// The contains() method tests if a specific item is contained within
// an object that implements Containment.
boolean contains(T o);
}
// Implement Containment using an array to hold the values.
class MyClass<T> implements Containment<T> {
T[] arrayRef;
MyClass(T[] o) {
arrayRef = o;
}
// Implement contains().
public boolean contains(T o) {
for(T x : arrayRef)
if(x.equals(o)) return true;
return false;
}
}
public class GenericsInterface {
public static void main(String[] args) {
Integer[] x = { 1, 2, 3 };
MyClass<Integer> ob = new MyClass<Integer>(x);
if(ob.contains(2))
System.out.println("2 is in ob");
else
System.out.println("2 is NOT in ob");
if(ob.contains(5))
System.out.println("5 is in ob");
else
System.out.println("5 is NOT in ob");
// The following is illegal because ob
// is an Integer Containment and 9.25 is
// a Double value.
// if(ob.contains(9.25)) // Illegal!
// System.out.println("9.25 is in ob");
}
}