0

I have a stack of Pair<String key, String value>, and I would like to see if my stack contains a specific value, for example,

private Stack<Pair<String key, String value>> store = new Stack<>();

store.push("cookie", "milk");
store.push("cookie", "white");
store.push("cookie", "triple");
store.push("pie", "apple");

I want to check, given my stack, if it contains "white", without popping everything off. If it contains white, then my methods are different to if it doesn't; there is a precedence in values. Like, if it contains white do x else do y.

I know that there is a method in the Stack class search(Object O), which returns the position in the stack if it does contain it, or a -1 if it doesn't, however, I am not sure how I would do this with a Pair. Would I have to do store.search("cookie", "white"), or can it be just the "white" value?

Naz1706
  • 5
  • 3

2 Answers2

0

Hi man i tried your example out and found out that there is no default implementation of Pairs in java so i searched and found this class which seems to do the job: https://stackoverflow.com/a/8446411/10721542

i then tested your example with the following code:

private static Stack<Pair<String, String>> store = new Stack<>();

    public static void main(String[] args){
        store.push(Pair.createPair("cookie", "milk"));
        store.push(Pair.createPair("cookie", "white"));
        store.push(Pair.createPair("cookie", "triple"));
        store.push(Pair.createPair("pie", "apple"));

        store.search(Pair.createPair("cookie", "white"));
    }

The only important thing that i found out is that your Pair implementation needs to have an equals implementation or else the search function will not work.

timmmmmb
  • 674
  • 7
  • 26
  • Sorry, you're absolutely right. I changed my code in the question, because I didn't want to get caught by turnitin, but needed to understand the concept of searching for a specific value in a stack of Pair elements. In reality, I have another class which deals with creating pairs, and pushing to the class containing the stack. But thank you, the store.search(Pair.createPair("cookie", "white")); method looks like it will work!! – Naz1706 Apr 29 '21 at 21:41
0

It seems you're creating an pair object, then inserting it into a hash. I would try

    store.search("white");

However, to search the stack, which contains objects, you might needs to construct a pair object containing "cookie" and "white" to search for object containing the values and not the actual values themselves.

I must ask, is there a reason you're using a stack to store key-pair values instead of a map or table?

  • Thank you! I think I'm going to try to create a Pair and search the pair! I'm just trying to implement something I found in a paper, and they mentioned using a stack – Naz1706 Apr 29 '21 at 21:44