1

i have the problem of not being able to call my own methods in object elements of an array

Here is the code for the part of the code with the array:

public class CardRules {
    private Object cardArray[];

public CardRules(Object cardArrayCopy[]){

    cardArray = cardArrayCopy;
    multiples();
}
public void multiples(){
for(Object ArrayElement: cardArray){
    System.out.println(ArrayElement);
}
}
}

And for the Card Object:

public class Card {
    private int rank;
    private int suit;
    private String Stringrank[] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    private String Stringsuit[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
    public static int CardNo = 0;

public Card(int cardDetails[]){
    rank = cardDetails[1];
    suit = cardDetails[0];
    CardNo++;
}
public String getCard(){
    return ("Card: " + Stringrank[rank] + " Of " + Stringsuit[suit]);

}
   public int getRank(){
       return rank;
   }
   public int getSuit(){
       return suit;
   }

}

The output for this part of the program is the hash codes, Card@9304b1 Card@190d11 Card@a90653 Card@de6ced Card@c17164

i would like to put something like or similar

System.out.println(ArrayElement.getRank());

does anyone have any ideas as to why this is happening?

btw the array is copied from an ArrayList in another class using the premade .toArray() method

2 Answers 2

3

The compiler can't know those objects are cards, since you declare them as Objects in the array. if you are sure that they will be cards, declare the array as Card (private Card cardArray[];) or cast them ((Card)ArrayElement).getRank().

If you want to check one more time, use ArrayElement instanceof Card to validate that this is a real Card instance before casting.

Sign up to request clarification or add additional context in comments.

1 Comment

If he has access to the other class where the ArrayList is converted to an array, he can also make it return an array of the Card type by passing the array to the toArray method. That way he could avoid the explicit casting on individual array elements. e.g. Card[] cardArray = (Card[]) list.toArray(new Card[array.size()])
0

System.out.println() invokes Object.toString(), So overwrite the toString() method of class Card. (btw: it's better to make the Stringrank and Stringsuit both static):

@Override
public String toString() {
    return String.format("Card [rank= %s, suit= %s]", 
           Stringrank[rank], Stringsuit[suit]);
}

1 Comment

Even better to declare them as enums. It's unlikely card ranks and suits will change anytime soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.