0

I had wrote my code for queue ADT but it is not generic. I don't know how to convert my code to generic ADT. Anyone can help me figure out how to change my code in order to make it become generic ADT

public class DeckQueue implements DeckInterface {

    private static final int ARRAY_SIZE = 10;
    private String[] cardArray = new String[ARRAY_SIZE];
public void enqueue(String newEntry) {
        for (int i = 0; i <= cardArray.length; i++) {
            if (cardArray[i] == null) {
                cardArray[i] = newEntry;
                break;
            }
        }
        
    }
    public String dequeue() {
        // get first element from array
        String front = null;

        if (!isEmpty()) {
            front = cardArray[0];

            // shift remaining array items forward one position
            for (int i = 0; i < cardArray.length - 1; ++i) {
                cardArray[i] = cardArray[i + 1];
            }
            //set last to null
            cardArray[cardArray.length - 1] = null;
        } else {
            System.out.println("Card is empty");
        }
        return front;
    }

    public boolean isEmpty() {
        return 0 == cardArray.length;
    }

    public void clear() {
        this.cardArray = new String[ARRAY_SIZE];
    }

    @Override
    public String toString() {

        for (int i = 0; i <= cardArray.length - 1; i++) {
            System.out.println(i + "=" + cardArray[i]);
        }
        return null;
    }
}

1 Answers1

0

The basic rules of thumb are:

  1. Start with the parent classes and interfaces. What methods does DeckInterface have and what types does it assume - should DeckInterface be generic itself?

  2. Add a type parameter for the class. For some reason single letters are frequently used, instead of something more descriptive. We'll use "E" to stand for "element":

public class DeckQueue<E> implements DeckInterface {
    ...
}
  1. Within the class, use this type parameter instead of the specific type, in both methods and instance variables. For example:
private E[] cardArray;

public void enqueue(E newEntry) {  ...  }

public E dequeue() {
    E front = null;
    ...
    return front;
}
  1. Solve remaining issues. For example: in this class you need an array of the generic type. It's not possible to do that directly, for good reasons, see How to create a generic array in Java? One way to get around it is adding a helper method:
private E[] cardArray = createArray();

@SuppressWarnings("unchecked")
private E[] createArray() {
    return (E[]) new Object[ARRAY_SIZE];
}
Joni
  • 101,441
  • 12
  • 123
  • 178