Ordered Collection doesn't grow.

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Ordered Collection doesn't grow.

Dominique Dartois-2
"I try to create a stream:"
st := ReadWriteStream on: (OrderedCollection new). "Display it"
"I add an element:"
st nextPut: 1.  "Display it"

I get the wallback:
Index 1 is out of bounds

I thought the collection was going to grow.
Somebody can give me some light??

Thanks to all.

----
Dominique Dartois


Reply | Threaded
Open this post in threaded view
|

Re: Ordered Collection doesn't grow.

Ian Bartholomew-17
Dominique,

> I thought the collection was going to grow.
> Somebody can give me some light??

It's all to do with the way Streams access their underlying collection.
Ignoring the WriteStream for the moment, what you are trying to do is
equivalent to

oc := OrderedCollection new.
oc at: 1 put: 'something'

This will fail because there is no "index 1" in the OrderedCollection.  You
have to add items, using #add:, before you can access or change them.

oc := OrderedCollection new.
oc add: 'anything'.
oc at: 1 put: 'something'

It is the #add: operation that causes the OrderedCollection to grow and this
then makes accessing via an index (where index <= the OrderedCollection's
size) possible.

(Aside)
You might then think that using the following would work...

oc := OrderedCollection new: 5.
oc at: 1 put: 'something'

... but it doesn't.  The argument specifies the size of the collection
before it needs to be grown, a sort of hint on the amount of slots that
might be needed. It does not actually #add: any items to the collection so
#at: still fails ...

oc := OrderedCollection new: 5.
oc size

... answers 0. You can't access a slot that doesn't exist.

(Back)
WriteStream and ReadWriteStream need an ArrayedCollection subclass to work
as WriteStream expects to be able to access it's collection using #at: and
#at:put: (and not #add). ArrayedCollection subclasses do also #grow in the
correct way and will work in your example because

oc := Array new: 5.
oc size    "answers 5"
oc at: 1   "-> ok"

I agree it is a bit confusing though. Collections that would normally be
expected to grow automatically (OrderedCollection) can't be used in a
WriteStream because they won't grow and Collections that wouldn't normally
grow (Array) must be used because they will !!

Regards
    Ian


Reply | Threaded
Open this post in threaded view
|

Re: Ordered Collection doesn't grow.

Dominique Dartois-2
Ian,
thank you for your explainations. I's a little bit confusing, as you said,
but you have explained it really clearly.

Thanks again.
----
Dominique Dartois