Search code examples
javaobjectarraylist

Do I need unique names for all my objects in a list?


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.


Solution

  • 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.