首页 > 解决方案 > 使用泛型实现打印特定对象属性的队列

问题描述

我创建了一个简单的 Queue 类型,它还包含一个 print() 函数。

公共类 ArrayQueue 实现队列 {

private T[] theArray;   
private int currentSize;    
private int front;  
private int back;

private static final int DEFAULT_CAPACITY = 10;


public ArrayQueue() {
    theArray = (T[]) new Object[DEFAULT_CAPACITY];
    currentSize = 0;
    front = 0;
    back = -1;
}


public boolean isEmpty() {
    return currentSize == 0;
}


public T dequeue() throws EmptyQueueException {
    if (isEmpty())
        throw new EmptyQueueException("ArrayQueue dequeue error");
    T returnValue = theArray[front];
    front = increment(front);
    currentSize--;
    return returnValue;
}


public void enqueue(T x) {
    if (currentSize == theArray.length)
        doubleQueue();
    back = increment(back);
    theArray[back] = x;
    currentSize++;
}


private int increment(int x) {
    if (++x == theArray.length)
        x = 0;
    return x;
}




public void print() {
    if (isEmpty()) {
        System.out.printf("Empty queue\n");
        return;
    }

    System.out.printf("The queue is: ");
    for (int i = front; i != back; i = increment(i)) {
        System.out.print(theArray[i] + " ");
    }
    System.out.print(theArray[back] + "\n");
}

我还创建了一个带有 3 个变量的 Song 对象

公开课歌{

private int id;
private String name;
private int likes;

public Song() {

    this(1,"Test",10);
}


public Song(int id,String name, int likes) {

}


public int getId() {
    return id;
}


public void setId(int id) {
    this.id = id;
}


public String getName() {
    return name;
}


public void setName(String name) {
    this.name = name;
}


public int getLikes() {
    return likes;
}


public void setLikes(int likes) {
    this.likes = likes;
}  

有没有办法修改此函数以打印特定对象的信息,或者我是否需要在实现过程中编写不同的打印方法?

例如,我希望我的 Print 方法显示所有对象变量,如果我像这样调用只会得到对象指针

ArrayQueue<Song> arrayQueue = new ArrayQueue<Song>();

Queue<Song> queue = arrayQueue; //arrayQueue instance is also a Queue


Song s = new Song();
arrayQueue.enqueue(s);
arrayQueue.print();

结果是

队列为:宋@15db9742

我的修改将打印:

队列是:1 测试 10

标签: javaobjectgenericsprintingqueue

解决方案


您需要覆盖 Song 的 toString() 方法。

例如,将其添加到 Song 中:

@Override
public String toString() {
    return id + " " + name + " " + likes;
}

推荐阅读