-1

I have created a priority Queue that holds songs with some attributes(id, title, likes). I want to print the heap, element by element on a format like this example:

5 ZZ TOP - La Grange 4167

instead it prints this:

[null, Song@330bedb4, Song@2503dbd3, Song@4b67cf4d, Song@7ea987ac... ]

This is my code:

 public class PriorityQueue<T> {
    private T[] heap;
    private int size;
    protected Comparator<T> cmp;

    public PriorityQueue(int capacity, Comparator<T> cmp){
        if(capacity < 1) throw new IllegalArgumentException();
        this.heap = (T[]) new Object[capacity + 1];
        this.size = 0;
        this.cmp = cmp;
    }

    public void print(T[] heap) {
        for (int i=1; i<=size; i++){
            System.out.print(heap[i]);
        }
        System.out.println();
    }

    public void insert ( T ob){
        if(ob == null) throw new IllegalArgumentException();
        if(size == heap.length - 1)throw new IllegalArgumentException();
        heap[++size] = ob;
        swim(size);
    }
}

somewhere on my main: (I put values in these variables)

Song s = new Song(id, title, likes);
System.out.println(s.getId() + " " + s.getLikes() + " " + s.getTitle());
pq.insert(s);
pq.print();
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
jasonjente
  • 23
  • 6
  • You need to override `toString` method in `Song`class – Amit Bera Nov 29 '18 at 15:44
  • 1
    Possible duplicate of [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – Roland Nov 29 '18 at 15:44
  • the question you ask in the title doesn't really match the output you show which doesn't really fit what else you did in your code.... so you know how to access an object inside an array (`array[index]`)... you know how to print your `Song` (`System.out.println(s.getId() + " " + s.getLikes() + " " + s.getTitle());`)... your output shows that you do not know `toString` and so it would be duplicate of the linked question... you may either want to update your question or lookup the referred question which has a very detailled answer regarding this topic.... – Roland Nov 29 '18 at 15:54

3 Answers3

0

In class Song add the method:

@Override
public String toString() {
    return getId() + " " + getLikes() + " " + getTitle();
}
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
0

When you call:

System.out.print(heap[i]);

What is printed is the result from the toString() method of you object. Your objects do not override a toString method so what you see is the result of the toString method from the Object class.

0

you haven't implemented the toString method in song class.

public class Song {

    @Override
    public String toString() {
        return s.getId() + " " + s.getLikes() + " " + s.getTitle();
    }

}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
shan
  • 112
  • 1
  • 9