August 9, 2008

Chapter: Holding Your Objects

Create and populate a List. Create a second List of the same size as the first, and use ListIterators to read elements from the first List and insert them into the second in reverse order.


In Java:
package chapter.holdingYourObjects;

import java.util.*;

public class Exercise12 {
public static void main(String[] args) {
List<Integer> x = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> y = new ArrayList<Integer>(x);

ListIterator<Integer> it = x.listIterator();
while(it.hasNext()) {
y.set(x.size() - it.nextIndex() - 1, it.next());
}

System.out.println("x = " + x);
System.out.println("y = " + y);
}
}

/* Output:
* x = [1, 2, 3, 4, 5]
* y = [5, 4, 3, 2, 1]
*/


In Python:
x = [1, 2, 3, 4, 5]
y = x[:]
y.reverse()

print "x = " + str(x)
print "y = " + str(y)


In Lisp:
(defparameter *x* '(1 2 3 4 5))
(defparameter *y* (reverse *x*))

(format t "x = ~s~%" *x*)
(format t "y = ~s" *y*)

0 comments: