KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > PurityTest


1 /**
2  * This example is from the article "A Combined Pointer and Purity Analysis for
3  * Java Programs" by Alexandru Salcianu and Martin Rinard.
4  * It is supposed to demonstrate the purity analysis (-annot-purity)
5  *
6  * by Antoine Mine, 2005/02/08
7  */

8
9 class List {
10
11     Cell head = null;
12
13     void add(Object JavaDoc e) {
14     head = new Cell(e,head);
15     }
16
17     Iterator iterator() {
18     return new ListItr(head);
19     }
20 }
21
22 class Cell {
23    
24     Object JavaDoc data;
25     Cell next;
26
27     Cell(Object JavaDoc d, Cell n) {
28     data = d;
29     next = n;
30     }
31 }
32
33 interface Iterator {
34     boolean hasNext();
35     Object JavaDoc next();
36 }
37
38 class ListItr implements Iterator {
39
40     Cell cell;
41
42     ListItr(Cell head) {
43     cell = head;
44     }
45
46     public boolean hasNext() {
47     return cell != null;
48     }
49
50     public Object JavaDoc next() {
51     Object JavaDoc result = cell.data;
52     cell = cell.next;
53     return result;
54     }
55 }
56
57 class Point {
58     
59     float x,y;
60
61     Point(float x,float y) {
62     this.x = x;
63     this.y = y;
64     }
65
66     void flip() {
67     float t = x;
68     x = y;
69     y = t;
70     }
71
72     void print() {
73     System.out.print("("+x+","+y+")");
74     }
75 }
76
77 public class PurityTest {
78
79     static float sumX(List list) {
80     float s = 0;
81     Iterator it = list.iterator();
82     while (it.hasNext()) {
83         Point p = (Point) it.next();
84         s += p.x;
85     }
86     return s;
87     }
88
89     static void flipAll(List list) {
90     Iterator it = list.iterator();
91     while (it.hasNext()) {
92         Point p = (Point) it.next();
93         p.flip();
94     }
95     }
96
97     static void print(List list) {
98     Iterator it = list.iterator();
99     System.out.print("[");
100     while (it.hasNext()) {
101         Point p = (Point) it.next();
102         p.print();
103         if (it.hasNext()) System.out.print(";");
104     }
105     System.out.println("]");
106     }
107
108     public static void main(String JavaDoc args[]) {
109     List list = new List();
110     list.add(new Point(1,2));
111     list.add(new Point(2,3));
112     list.add(new Point(3,4));
113     print(list);
114     System.out.println("sum="+sumX(list));
115     sumX(list);
116     print(list);
117     flipAll(list);
118     print(list);
119     }
120 }
121
Popular Tags