Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<E> Implementations

Tags:

java

list

I'm creating a simple Game of War with cards for my Data Structures class.

I currently have a method as follows:

Play Turn(List<Card> player1, List<Card> player2){
    return null;
}

The above method (which I understand is incomplete currently) is suppose to accept any subinterface of the List interface(i.e. Stack, ArrayList, LinkedList, etc.).

The Stack uses pop() to return/remove the top of the Stack, and something like an ArrayList or LinkedList I can use the get() method to return the first element and then the remove() method to remove that element.

So is there a way that I can do this in a generic way, or do I have to create a method tailored to each version of List I allow to be used?

like image 663
Ryley6905 Avatar asked Jun 05 '26 09:06

Ryley6905


1 Answers

Please learn and follow the Java coding standards (Google or Sun/Oracle). Your code is less understandable without them.

Your method should look like this:

Play turn(List<Card> player1, List<Card> player2) {
    return null;
}

The meaning is clear: You can pass any reference to an Object on the heap that implements the List interface. It means that your implementation should only call methods in the List interface. You should not be concerned with the concrete implementation of the reference you're given.

I don't understand where Stack plays in this interface. A Stack might be implemented using a List, but its methods (push, pop, peek) are not part of the List interface. They'll be off limits to the parameters in your interface.

If you think your methods needs a Stack<Turn> for each player, then you should not have a List as parameter.

like image 80
duffymo Avatar answered Jun 06 '26 22:06

duffymo