如何使用indexOf方法

时间:2015-05-27 19:36:26

标签: java arraylist collections indexof

我有对象Song的ArrayList。每个Song都有自己的参数title, composer, duration,。我正在尝试编写将要查找title的{​​{1}}的方法,并使用此参数向我提供ArrayList中对象的object SongINDEX是ArrayList的名称

songs

在这种情况下,方法是查找名为public int findSong(String title) { int index = songs.indexOf(title); System.out.println(index); return index; } 的Object,但是如何编写他将要查找具有参数{{1的对象的help的方法等于index。我只想了解逻辑)

title

5 个答案:

答案 0 :(得分:2)

试试这段代码:

public int findSong(String title) {
    int index = -1;
    // Iterate over the elements of the list
    for (Song song : songs) {
        if (song.getTitle().equals(title)) index = songs.indexOf(song);
    }
    // If you didn't know here we have if / else
    // if index == -1 print song not found else print the index
    System.out.println(index == -1 ? "Song not found: " + title : "Sound found at index " + index);
    // If song isn't found index is -1
    return index;
}

编辑: Max Zoom在评论中说道

  

如果有一首歌具有给定标题的情况怎么样?

代码:

public int[] findSong(String title) {
    List<Integer> indexesList = new ArrayList<>();
    // Iterate over the elements of the list
    for (Song song : songs) {
        if (song.getTitle().equals(title)) indexesList.add(songs.indexOf(song));
    }
    // If we have no songs return empty array
    if (indexesList.size() == 0) return new int[0];
    // Convert list to int array
    int[] indexes = new int[indexesList.size()];
    for (int i = 0; i < indexes.length; i++) {
        Integer integer = indexesList.get(i);
        if (integer != null) indexes[i] = integer.intValue();
        else indexes[i] = -1;
    }
    return indexes;
}

答案 1 :(得分:1)

public int findSong(String title, List<Song> songs) {

    for (Song song : songs) {
      if (song == null || song.getTitle() == null) {
        continue;
      }
      if (song.getTitle().equals(title)) {
       int index = songs.indexOf(song);
       System.out.println(index);
       return index;
      }
    }
    return -1;

}

答案 2 :(得分:0)

如果两首歌曲名称相等,您可以覆盖Song班级的相等功能以返回true

public class Song{

    //Your other fields and functions ....

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Song))
            return false;
        if (obj == this)
            return true;

        Song s= (Song) obj;
        return s.getTitle().equals(this.title);
    }

}

答案 3 :(得分:0)

file()

答案 4 :(得分:0)

def my_controller_action
  # ...
  if request.xhr?
    render :layout => 'other_layout_with_flash_messages'
  end
end