简体   繁体   English

Smalltalk中真的没有预定义的动态2D容器吗? 我必须自己做吗?

[英]Is there really no predefined dynamic 2d container in Smalltalk? Do I have to make my own?

I need a dynamic 2d container and I was suprised that I could not find anything usefull in the Collections. 我需要一个动态的2D容器,但令我感到惊讶的是,我在Collections中找不到任何有用的东西。 So I made my own in oldskool fashion but somehow I feel like there must be somthing im missing. 因此,我以过时的方式制作了自己的作品,但以某种方式,我觉得一定缺少某种东西。 The whole concept in smalltalk pharo is based on using their stuff instead of having to build your own. smalltalk pharo中的整个概念基于使用他们的东西,而不必自己构建。

OK, so you want to have a collection of objects (morphs in your case) arranged by rows and columns. 好的,因此您希望有按行和列排列的对象集合(在您的情况下为变形)。 Here is one way to do this 这是一种方法

  1. Initialization: Create an instance variable in your class for holding the objects, and initialize it as: 初始化:在类中创建一个实例变量来保存对象,并将其初始化为:

     morphs := OrderedCollection new 
  2. Addition: Place new objects in your collection by means of a method like this one 加法:通过这种方法将新对象放入您的集合中

     placeMorph: morph atRow: i column: j | row | row := morphs at: i ifAbsentPut: [OrderedCollection new]. j - row size timesRepeat: [row add: nil]. row at: j put: morph 

Note that by adding nil exactly j - row size times (which could be <= 0 ) ensures the existence of a slot at row i column j . 需要注意的是通过添加nil准确j - row size倍(其可以是<= 0 )可确保在排狭槽的存在ij

  1. Retrieval : Get the object at a given position in the grid or nil 检索 :在网格或nil的给定位置获取对象

     morphAtRow: i column: j | row | row := morphs at: i ifAbsent: [^nil]. ^row at: j ifAbsent: [nil] 

Another possibility would be to use a Dictionary , which could make sense if the grid is large and sparse. 另一种可能性是使用Dictionary ,如果网格很大且稀疏,这可能很有意义。 In that case you could do the following 在这种情况下,您可以执行以下操作

  1. Initialization 初始化

     morphs := Dictionary new 
  2. Addition 加成

     placeMorph: morph atRow: i column: j morphs at: i -> j put: morph 
  3. Retrieval 恢复

     morphAtRow: i column: j ^morphs at: i -> j ifAbsent: [nil] 

Note that I've used associations i -> j for the keys. 请注意,我已经使用关联i -> j作为键。 Another possibility would have been to use pairs {ij} . 另一种可能是使用对{ij}

Pharo has Matrix class. Pharo具有Matrix类。 That's pretty much a 2d container, unless you are talking about something else I do not understand :) 那几乎是一个2D容器,除非您正在谈论我不明白的其他事情:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM