-1

I created a user defined class pair to add two elements in stack. But how can I use peek function of the stack? I want to access the "element" of pair class using peek.

import java.util.*;
public class Example {
    public static class pair{
        int element;
        int idx;
        public pair(int element, int idx){
            this.element = element;
            this.idx = idx;
        }
        
    }
    public static void main(String[] args) {
        Stack<pair> st= new Stack<pair>();
        pair p1 = new pair(100,2);
        st.push(p1);
        System.out.println(st.peek());
    }
}
  • When I am trying to print st.peek() I got output: Example$pair@4617c264

2 Answers2

1

You need to override toString() in your pair class.

@Override
public String toString() {
   return element + ", " + idx;
}

This is an example. It is up to you what you want returned in the string. You could also do something like:

return "Element = %d, Idx = %d".formatted(element, idx);
WJS
  • 36,363
  • 4
  • 24
  • 39
0

"... But how can I use peek function of the stack? ..."

The Stack#peek method is going to return the object, in this case a pair.

"... I want to access the "element" of pair class using peek ..."

You can access the element field via dot-notation.

st.peek().element

"... When I am trying to print st.peek() I got output: Example$pair@4617c264"

This is just a naming scheme used by Java, which will be returned when trying to convert an Object to a String.

The System#out#println method is taking an Object as a parameter, not a String.

Here is the source, for println.
GitHub – jdk/src/java.base/share/classes/java/io/PrintStream.java.

Which is using the following, more-or-less—where x is of type, Object.

String s = String.valueOf(x);

An Object can provide a String resolution by overriding the inherited Object#toString method.

Here is the source, for Object#toString.
GitHub – jdk/src/java.base/share/classes/java/lang/Object.java.

So, if you wanted, you can add a toString method, to your pair class.

public static class pair{
    int element;
    int idx;
    public pair(int element, int idx){
        this.element = element;
        this.idx = idx;
    }

    @Override
    public String toString() {
        return String.valueOf(element);
    }
}

Then, when using the following,

System.out.println(st.peek());

You're output will be,

100
Reilas
  • 3,297
  • 2
  • 4
  • 17