Piotr Badura
Piotr Badura

Reputation: 1672

Searching in Hashcode doesn't work in Java

I Have a

Set tablica = new HashSet();

And I want to search it so I wrote something like this:

public void searchStudentbySurname() {
    int a = tablica.size();
    if (0 >= a) {
        JOptionPane.showMessageDialog(null, "No data");
    } else {
        String S = JOptionPane.showInputDialog(null, "Give me a surname");
        Iterator itr = tablica.iterator();
        while (itr.hasNext()) {
            String str = (String) itr.next();
            if(tablica.equals(S)) {    // this if doesn't work (1)
                JOptionPane.showMessageDialog(null, str);
            }

        }

    }

}

}

I want to know why (1) doesn't work.

Upvotes: 1

Views: 76

Answers (3)

sol4me
sol4me

Reputation: 15698

if(tablica.equals(S)) 

doesn't work because you are comparing objects of 2 different types (Set and String). You can use contains that

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Upvotes: 0

kmandov
kmandov

Reputation: 3209

You want to compare the item in tablica to the user input.

Should be:

if(str.equals(S)) { 

Upvotes: 0

Eran
Eran

Reputation: 393771

You are comparing a String to a Set, so it's can't return true.

You probably meant to compare it to str - str.equals(S), but even that is not necessary. You can simply replace the entire while loop with tablica.contains(S). That's what Sets are for.

Upvotes: 2

Related Questions