Home Set<> is giving different objects for same value
Reply: 0

Set<> is giving different objects for same value

user10740
1#
user10740 Published in September 19, 2018, 9:39 am

Hi i am trying to implement a SQLite based Application and have some values in the table of my database. one of my column contains some similar values and to overcome the duplication , I used set<>

public Set<NewTableAnswers> newtableAnswers(String product_id) {
    Set<NewTableAnswers> d = new HashSet<>();
    SQLiteDatabase db = this.getReadableDatabase();

    String SelectA1 = "SELECT * FROM " +TABLE_ANSWERS+ " WHERE " + ANSWER_ID + " = '"+ product_id + "' ";
    Cursor cursor = db.rawQuery(SelectA1,null);
    if (cursor.moveToFirst()){
        do{
            d.add(new NewTableAnswers(cursor.getString(1)));
        }while (cursor.moveToNext());
    }
    db.close();
    return d;

if there is a duplicate, set should follow its property to avoid duplicates, but its giving me same value with different objects..like this...

Update:

this is my model class..

public class NewTableAnswers {

String pro_id;

public NewTableAnswers(String pro_id) {
    this.pro_id = pro_id;
}

public String getPro_id() {
    return pro_id;
}

public void setPro_id(String pro_id) {
    this.pro_id = pro_id;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof NewTableAnswers)) return false;
    NewTableAnswers that = (NewTableAnswers) o;
    return Objects.equals(getPro_id(), that.getPro_id());
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public int hashCode() {

    return Objects.hash(getPro_id());
}

}

Image of the Database

share|improve this question
  • 7
    Did you override equals and hashCode? – Eran Apr 17 at 7:30
  • 1
    for that you have to implement equals and hashcode properly – Blackbelt Apr 17 at 7:30
  • 2
    Possible duplicate of Why do I need to override the equals and hashCode methods in Java? – HBo Apr 17 at 7:31
  • 3
    We can't help you without seeing the implementation of NewTableAnswers, in particular (as @Eran said) equals and hashCode. Read the Set documentation for why. – T.J. Crowder Apr 17 at 7:31
  • 2
    FYI: Eran and Blackbelt mean that you should implement those methods in class NewTableAnswers – Jack Flamp Apr 17 at 7:31

1 Answer 1

active oldest votes
up vote 1 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.570859 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO