In general, there is an array that implements the ArrayList<MyModel> model. How to implement a search on it?

 if(MyPlayer.LastPlay.contains(t)==true){ } 

t type String . Returns always false . Even if there is such a string in the array

Model code

 public class ModelMusic { String title; String album; String src; ModelMusic(String t, String a, String s){ title=t; album=a; src=s; } public String getTitle(){ return title; } public String getAlbum(){ return album; } public String getSrc(){ return src; } } 

Closed due to the fact that the question is not clear to the participants by Alex , PashaPash , Athari , Streletz , Vladyslav Matviienko 18 Nov '15 at 5:33 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Please expand the question. I do not think that the answer "use list.indexOf " will suit you - zRrr
  • I need to check whether there is a specific string in the array. List.contains (string) does not want to work - user186301
  • 2
    Give a piece of code, describe what data you send to the input, what you expect to receive and what you actually get. - zRrr 4:34
  • Updated the answer ........................ - user186301
  • I would venture to suggest that either LastPlay does not contain any strings, but some other objects, or you are trying to check for the presence in the list of a string containing the substring t . Show the announcement MyPlayer.LastPlay . - zRrr

1 answer 1

List.contains(Object o) checks the equality of the object in the list to the method parameter via o.equals . Since you have other objects in the list, String.equals never returns true . Therefore, it is necessary to check the equality of a specific field. For convenience, you can wrap the search in a separate method:

 private static ModelMusic findSongByTitle(List<ModelMusic> list, String title) { for ( ModelMusic song : list ) { if ( title.equals( song.getTitle() ) ) { return song; } } return null; } 

The method assumes that the list does not contain null , and the title also not null .

Using Stream you can write more like this:

 Optional<ModelMusic> r = lastPlay.stream() .filter( song -> song.getTitle().equals(t) ) .findAny();