Domanda

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?

È stato utile?

Soluzione

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());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top