1

I have a Card class and now I want to create a Deck class. I'm looking at what's available in Collections to store the list of cards, knowing that I will need as much freedom in manipulating the cards as possible.

I want be able to insert new cards anywhere in the deck, shuffle them (Collections.shuffle() should work), peek at any card and take (remove) cards from the top, bottom and anywhere in the middle. Anything you can do with a pile of cards should be possible. No "only LIFO" restriction for example.

Here is what I have found so far and my issues with each:

  • List: seems to provide as much freedom as I need but, clearly, I would need to add some helper functions for the simpler things such as picking the card on top. Still my favored solution for now.
  • Stack: potentially does all I'm asking, but, from what I've read, is not the best implementation (extends Vector and is not just a stack in its behavior?)
  • Deque: has functions I would like but does not seem to allow insertion of new items at any index (nor "getAt(index)" afaik)

Is there a premade class that's better than any of the above for what I'm trying to do? If nothing "perfect" exists, which class should I use as a base for expansion instead?

Of note: I do not know if I care about synchronization for now. I'm also looking at this from a Java 6 perspective, but I'm open to Java 7 solutions, especially if there's a ready-made solution for it.

4

4 回答 4

9

我会采用List基于 - 的方法。您的要求相当模糊,但 aList为您想要做的事情提供了良好的基础。我建议List在你的Deck类中包装 a (而不是Deck扩展一个具体的List类,例如ArrayListor LinkedList)。所有Deck行为都应该由Deck类定义;您当然不想自动继承所有List行为,因为它可能并不都适合您的Deck对象。

于 2013-07-02T19:41:12.090 回答
2

在 Arraylist 上寻找LinkedList 。

链接列表为您提供了您正在查看的 Deque 的所有功能,并且还允许插入和检索以及索引点。仍然允许 shuffle 并且还具有数组列表不允许的 peek 方法。它也有像栈一样的 push 和 pop 方法

于 2013-07-02T20:46:31.130 回答
0

我会使用 ArrayList,你仍然可以使用 collections.shuffle(),它在获取和添加元素时提供了恒定的时间开销。

于 2013-07-02T19:43:30.647 回答
0

您是否考虑过使用普通的旧数组?
您可以简单地将卡片向前推并插入打开的插槽,随时从任何插槽中选择任何内容,将其洗牌,以及您可能需要做的任何其他事情。这更好地包裹在一个类中。

优点:
- 比 Java API 中的任何列表/地图/设置类更快、更轻。

缺点:
- 您需要编写(非常基本的)方法来操作数组。

于 2013-07-02T19:46:46.303 回答