Add to a collection

Richard A. O'Keefe ok at cs.otago.ac.nz
Tue Feb 4 02:07:48 UTC 2003


Janet Abdul-Karim <jn_karim at yahoo.com> wrote:
	I created a subclass to ordered collections.

Unless you are inventing a new kind of collection data structure,
you probably don't want to do that.

We could have hours of fun debating whether a portfolio
*is* a collection of accounts or *has* a collection of
accounts, but the simplest way to look at it may be this:
    If your class INHERITS from Collection, then
    (a) you have the obligation to make sure that all of the methods
        in the interface of Collection WORK for your class, or are
        explicitly cancelled.  Collection is pretty big in Squeak,
        you probably don't want to do that.
    (b) you inherit EVERYTHING from Collection, including methods
        that change the object in ways you probably don't want to
        happen.


	I am trying to add objects to the new class

Presumably you mean "add objects to AN INSTANCE OF the new class".

	and then print it to make sure they are in there.

Good.

	I add one object it prints but when I add another object and
	print it only prints the first object i added
	
	sample code to add to list.
	
	account: aAccount
	 "Add an account to the portfolio"
	
	 self isNil ifTrue:[self add: aAccount]
	  ifFalse:[ self addLast: aAccount].
	
The only object for which 'self isNil' can ever be true is nil.
nil is the unique instance of UndefinedObject.
nil is NOT an instance of your class.
Your code can be simplified to

	addAccount: anAccount
	    self addLast: anAccount.

	code to print list. 
	
	accounts
	 "Returns the accounts for the portfolio"
	
	 self do:[:element|^element number].
	 
(1) That code doesn't print anything.
(2) Did you notice that little caret in there?
    What your code says is
	"For each element in myself
	    RETURN the element's number STRAIGHT AWAY RIGHT NOW!
	    (and don't look at any other elements)."

    This is almost the same as
	^self first number

Change the code to

	accountNumbers
	    "Answer the account numbers of all the accounts
	     in the portfolio."
	    ^self collect: [:each | each number]
	



More information about the Squeak-dev mailing list