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

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Samual
  • 11
  • 1

2 Answers2

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • 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()])` – Cristian Sanchez May 16 '11 at 04:55
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]);
}
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130