Java Reference
In-Depth Information
Consider the following client code, which performs parallel operations on two dif-
ferent lists, adding three values, removing one, and printing the list before and after
the remove:
1 public class ListClient1 {
2 public static void main(String[] args) {
3 ArrayIntList list1 = new ArrayIntList();
4 list1.add(18);
5 list1.add(27);
6 list1.add(93);
7 System.out.println(list1);
8 list1.remove(1);
9 System.out.println(list1);
10
11 LinkedIntList list2 = new LinkedIntList();
12 list2.add(18);
13 list2.add(27);
14 list2.add(93);
15 System.out.println(list2);
16 list2.remove(1);
17 System.out.println(list2);
18 }
19 }
The program produces the following output:
[18, 27, 93]
[18, 93]
[18, 27, 93]
[18, 93]
As we expected, the two kinds of list behave the same way. So what if you wanted
to introduce a static method to eliminate this redundancy? What type would you use
for the parameter? You can't use ArrayIntList because then you wouldn't be able
to pass the LinkedIntList as a parameter, and vice versa.
As we saw in Chapters 9 and 11, the right way to approach this task is to intro-
duce an interface. You want to think of these lists as being the same kind of thing.
Even though you recognize that there are significant differences between the two,
you can imagine an “integer list” abstraction of which these are two possible
implementations. They're the same in the sense that they provide basic “integer
list” functionality like an appending add. But they are different in the sense that
they are implemented quite differently (one using an array and the other using a
linked list).
Search WWH ::




Custom Search