gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:05:35 27 4
gpt4 key购买 nike

我有对象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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com