java - 如何使用 indexOf 方法在 arraylist 中查找对象(具有自己的参数)的索引

标签 java arraylist collections indexof

我有对象Song 的ArrayList。每首 Song 都有自己的参数,title, composer, duration,。我正在尝试编写将查找 object Songtitle 的方法,并将给我该对象的 INDEX带有此参数的 ArrayList。 songs是ArrayList的名字

public int findSong(String title) {
        int index = songs.indexOf(title);

        System.out.println(index);
        return index;
}

在这种情况下,方法正在寻找名称为 help 的对象,但是如何编写他将寻找对象的 index 的方法具有等于​​ help 的参数 title。我只是想了解逻辑)

 classname.findSong("help");

最佳答案

试试这段代码:

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 在评论中说

How about the case where there is more then one song with given title?

代码:

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;
}

关于java - 如何使用 indexOf 方法在 arraylist 中查找对象(具有自己的参数)的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491614/

相关文章:

java - 编译为 Java 字节码并可以在 JVM 上运行的语言

java - "Cannot Find Symbol"构造函数中出现错误,并将 ArrayList 在类之间传递

java - 匹配两个列表值,最终得到具有不同值的最终列表

Java:如何初始化类型化对象列表?

带有 .* 的 Java 正则表达式组与普通正则表达式

java - 使用 JUnitCore 运行参数化测试

java - 使用消息 "message": "Content type ' text/plain;charset=UTF- 8' not supported" 测试 Post API 时获取 415 状态代码

java - 如何选择 ArrayList 中元素的索引并更改其属性之一?

java - "Comparison method violates its general contract!"但我只比较两个长值?

java - 使用 Collection 对 ArrayList 进行排序的问题