August 9, 2008
at
Saturday, August 09, 2008
Labels:
Computer Science,
Java,
Lisp,
Python,
Thinking in Java
Posted by
Billy
Chapter: Holding Your Objects
Create a class, then make an initialized array of objects of your class. Fill a List from your array. Create a subset of you List by using subList(), then remove this subset from your list.
In Java:
package chapter.holdingYourObjects;
import java.util.*;
class MyClass {}
public class Exercise7 {
public static void main(String[] args) {
MyClass[] myClassArray = {new MyClass(), new MyClass(), new MyClass()};
List<MyClass> myClassList = new ArrayList<MyClass>(Arrays.asList(myClassArray));
// Can't use sublist because removeall won't work
List<MyClass> sublist = Arrays.asList(myClassList.get(0), myClassList.get(1));
System.out.println("myClassList = " + myClassList);
System.out.println("sublist = " + sublist);
myClassList.removeAll(sublist);
System.out.println("myClassList = " + myClassList);
}
}
/* Output:
myClassList = [chapter.holdingYourObjects.MyClass@3e25a5, chapter.holdingYourObjects.MyClass@19821f, chapter.holdingYourObjects.MyClass@addbf1]
sublist = [chapter.holdingYourObjects.MyClass@3e25a5, chapter.holdingYourObjects.MyClass@19821f]
myClassList = [chapter.holdingYourObjects.MyClass@addbf1]
*/
In Python:
class MyClass():
pass
myClassArray = [MyClass(), MyClass(), MyClass()]
sublist = myClassArray[0:2]
print "myClassArray = " + str(myClassArray)
print "sublist = " + str(sublist)
for item in sublist:
myClassArray.remove(item)
print "myClassArray = " + str(myClassArray)
#>>> ## working on region in file /tmp/python-7533hFb...
#myClassArray = [<__main__.MyClass instance at 0xb7d9ee8c>, <__main__.MyClass instance at 0xb7d9ef0c>, <__main__.MyClass instance at 0xb775830c>]
#sublist = [<__main__.MyClass instance at 0xb7d9ee8c>, <__main__.MyClass instance at 0xb7d9ef0c>]
#myClassArray = [<__main__.MyClass instance at 0xb775830c>]
In Lisp:
(defclass MyClass () ())
(defparameter *MyClass-array* (list (make-instance 'MyClass)
(make-instance 'MyClass)
(make-instance 'MyClass)))
(defparameter *sublist* (butlast *MyClass-array* 1))
(format t "MyClass = ~s~%" *MyClass-array*)
(format t "sublist = ~s~%" *sublist*)
(loop for item in *sublist* do
(setf *MyClass-array* (remove item *MyClass-array*)))
(format t "MyClass = ~s~%" *MyClass-array*)
;;;Output:
;MyClass = (#<MYCLASS #x20513866> #<MYCLASS #x20513876> #<MYCLASS #x20513886>)
;sublist = (#<MYCLASS #x20513866> #<MYCLASS #x20513876>)
;MyClass = (#<MYCLASS #x20513886>)
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment