0

I am a first year Comp Sci student. For part of an assignmentI have for my Java class. I need to create a deck class that is an ArrayList containing Card objects.

Here is an example of a card object I have coded:

public class Card
{
    // instance variables 
    private int face;
    private int suit;

    /**
     * Constructor for objects of class Card.
     * Note: Hearts = 1, Diamonds = 2,
     * Spades = 3, Clubs = 4
     * 
     * All face cards equal their common value
     * Ex. A = 1
     */

    public Card(int face, int suit)
    {
        // initialize instance variables
        this.face = face;
        this.suit = suit;
    }
    
    public int getFace()
    {
        return face;
    }
    
    public int getSuit()
    {
        return suit;
    }
    
    public String toString()
    {
        return face + "" + suit;
    }
}

I understand how to load the "deck" up with each individual card a standard deck. I am just having trouble fathoming how I can give each card a unique name. For example, how to display the cards face and suit to the screen so the player can see in their hand? (We are also supposed to make a class with a list of the cards in the players hand.)

If I make a list of card objects, would I just call on their individual methods by somehow referencing the slot they are in? How would I do that? And if I move them from the deck to a hand would that change it?

Normally when you use a method for an object you have the object created with a name (let's say, card1). Then to call on a method using that cards data you would say card1.getSuit() if I wanted to return the suit value. But I don't know how to do that when creating many objects in a list.

I feel like I am probably overcomplicating things in my brain but I think it's better to understand different angles of Java better anyways so I like asking these kinds of questions. Thanks to anyone who can help!

Note: I am just starting my second semester Java course so the farthest we have gotten is maybe like inheritance. We aren't expected/supposed to know about things like enums, constant lists or anything more complicated I guess. I hear we will be doing a lot of JavaFX though.

5
  • 2
    would I just call on their individual methods by somehow referencing the slot they are in? - yes. Read the ArrayList API for the methods that will allow you to access the cards.
    – camickr
    Commented Jan 21 at 0:55
  • 2
    You don't create an object with a name. You can declare a variable which holds a reference to an object, but the name card1 is the name of the variable, not the name of the object. It can hold a reference to any instance of Card.
    – tgdavies
    Commented Jan 21 at 1:00
  • Probably you should just try it. The code above looks like it was supplied to you. Try writing some code on your own. When you get stuck, ask a question about that code. If it helps, I think you will need four loops. Each loop assigns the numbers to cards (easy to do with a loop), and the four loops together create each of the Hearts, Diamonds, Spades and Clubs suits.
    – markspace
    Commented Jan 21 at 5:08
  • Thanks for your help everyone. Also, the only thing I was given for my assignment was what to call the classes and instance variables, and which numbers should represent which suit, I wrote everything myself! (Flattered that you think I was given this though I guess so my coding must be at least somewhat good). And I already know what to do with the loops btw. I was sick one of the days we learned about ArrayLists in class so I could have missed something key that answers my question. I appreciate the answers either way though so thanks again. Commented Jan 21 at 14:53
  • By the way, watch out for run-on sentences. After writing a draft, go back to edit for clarity. I did a bit of that for you today. Take care when posting here. Stack Overflow is meant to be more like Wikipedia, less like a casual chat room. Tip: Clear writing will aid your career. Commented Jan 21 at 22:00

4 Answers 4

2

No,you can store the reference of the object in the list rather than creating an individual object with different name.

List<Object> ls = new ArrayList<>();
 //for adding obj into it 
ls.add(new Card(face,suit));
 //for getting data
ls.get(index).getFace();

By this way you can add many object in list rather than giving different name.

1
  • Thanks, this exactly answers my question! I figured the solution would be something close to this I just didn't know how to do it exactly Commented Jan 21 at 15:00
0

Think of human to be a class, and every human being to be an instance of this class. Do all human beings need to have unique names? How many 'Joe's or 'Alan's do you know? And is a human being limited to one name only or can it have several? (my mom calls me ..., but my friends call me ...)

Names are used to reference humans, same as pointers can reference objects.

But be aware: if Java sees no reference to an object and it is not alive (speak no thread running in it), it will be garbage collected and discarded.

0

The short answer is no. There are multiple ways to store references to objects. You often store a reference to a single "higher order" object which has references to several other objects, which have references to... (you get the idea).

First of all, Card card1 = new Card(...) does NOT read "creating an object with a given name, i.e. card1". Instead, it is storing a reference to the newly created Card object in the card1 variable (of type Card) defined in the current scope.

When you don't care about individual cards, but only need to store them as a group, they do not need individual "names". If you define a hand to be an array/List/... of cards, you should store that as a whole in a variable of the corresponding type (Card[], List<Card>, your own custom Hand class etc.):

Card[] hand = new Card[] { new Card(...), new Card(...), new Card(...), ... };

You haven't assigned an individual "name" for each card, but you are holding a hand (pun intended), which in this case is just a Card array. Now to use the individual cards within this hand (when needed), you can just iterate through them or access them by position:

// for the limited scope of the for loop,
// you give each card in the hand the same "name" (i.e. card)
// just to refer to it until you move on to the next card.
for (Card card : hand) {
    if (card.getFace() > ...) ....
}

// you can also refer to (say) the 2nd card in your hand,
// without giving it a "name" at all (not even temporary):
if (hand[1].getSuit() == ....) ....

As a side note, you should probably not use an array in this case (and not even a List), but write a proper Hand class that encapsulates the internal representation -- but that's an entirely different concern.

1
  • Thank you so much this explained things really well! I didn't want to go further into what I am actually doing as I don't want to be given the answers and I want to learn how to do things- that being said yes, for my project I am doing a card game so my professor wants us to make card objects, make an ArrayList of card objects that represents a deck (and have a standard 52 deck of cards so every card exists), then have a hand class to move cards from the deck to a hand that could be used for gameplay you're exactly right! Just wasn't as relevant to my question in this case Commented Jan 21 at 15:29
0

Reference to an object

when you use a method for an object you have the object created with a name (let's say, card1)

Card card1 = new Card ( … ) ;

The catch here, the crucial thing to understand, is that card1 does not hold a Card object. The variable named card1 holds a reference (a pointer) to a Card object that lives elsewhere, floating around some place in memory.

The new command does not return a Card object. The new command constructs a Card object somewhere in memory, and then returns a reference to that object. You can think of the reference as a tether the leads you to the object.

So your statement quoted above is incorrect technically. card1 is not the name of an object. card1 is the name of a variable holding a reference to an object.

An element in a List is another place you can put a reference.

List < Card > deck = new ArrayList<>() ;
deck.add( card1 ) ;

That second line copied the reference held in card1 variable into a slot of the ArrayList. Now we have one Card object, and two references that lead to that object.

Similarly, we can directly assign the reference returned by new to a slot in the ArrayList:

deck.add( new Card ( … ) ) ;  // Store a reference to the new object as an element in this list. 

By the way, when all of those references are cleared from memory, the Card object remains! At that point the Card object becomes a candidate for garbage collection, to be eventually cleared from memory. Until that g.c. operation executes, we have one object and zero references.

Not the answer you're looking for? Browse other questions tagged or ask your own question.