list.contains()在android中不起作用

Abd*_*eet 2 android arraylist

list.contains不起作用.这是我从数据库中获取数据的列表.

////////List/////////////////
public List<Comment> getAllComments() {
        List<Comment> comments = new ArrayList<Comment>();

        Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
                allColumns, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Comment comment = cursorToComment(cursor);
            comments.add(comment);
            cursor.moveToNext();
        }
        // make sure to close the cursor
        cursor.close();
        return comments;
    }
/////////////////////////////////////////////





    datasource = new CommentsDataSource(this);
        datasource.open();
        final List list;
        list = datasource.getAllComments();

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
if(list.contains("Hello")){
                    Toast.makeText(getApplicationContext(), "List Contains data", Toast.LENGTH_SHORT).show();
                } ///////Here it always return false///////
else{
 Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_SHORT).show();
}
            }
        });
}
////////////////////////////////////////////////////
Run Code Online (Sandbox Code Playgroud)

我的列表包含你好,但我不知道为什么它不起作用.对不起,如果已经被问到.事情是我想要一些示例代码,关于我的代码提前谢谢.

Jos*_*iro 7

我认为你必须覆盖Comment类中的equals()方法.就像是

 @Override
 public boolean equals(Object obj) {
     if (this.message.equals(((Comment)obj).getMessage()) {
         return true;
     }

     return false;
 }
Run Code Online (Sandbox Code Playgroud)

在此示例中,消息将是您要比较的类的属性,您可以按如下方式执行此操作

if(list.contains(new Comment("Hello")){
   ...
Run Code Online (Sandbox Code Playgroud)

问候!