1

Stack has methods peek() and pop(), which affects the object on top of the stack, but since it inherits from other Classes, are there methods that can peek at eg. 4th element of the stack and pop 3rd element?

Why am I asking? I need to store 5 cards as a hand in five card draw game. I'd like to sort it from lowest to biggest value, and later get rid of few cards. Additional question: is it good idea to use stacks for it?

Naan
  • 521
  • 1
  • 11
  • 28
  • hand-strength in five card draw is not (only) related to each individual card's value (you wrote you wanted to sort "lowest to bigges"). If you have four deuces and one five, taken individually the 5 is stronger than any 2. Yet the 5 is precisely the card you may want to consider changing. – TacticalCoder Nov 04 '13 at 20:44

1 Answers1

1

You can use an ArrayList and then use the get(index) for peekAt() and remove(index) for popAt() functionalities. Also, you can sort you ArrayList using Collections.sort() and in case the elements of the ArrayList are going to be your custom class objects, you can sort them by providing your own customer comparator.

Normal sort:

Collections.sort(list);

Custom sort:

public class MyComparator implements Comparator<MyClass>{
    @Override
    public int compare(MyClass o1, MyClass o2) {
        // Your comparison logic
    }
} 
...
Collections.sort(list, new MyComparator());
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • compare() return's {-1; 0; 1} ? – Naan Nov 02 '13 at 11:44
  • Its more of like, negative integer, 0 and positive integer. Have a look at [the docs](http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) for more detailed info. – Rahul Nov 02 '13 at 11:52