【发布时间】:2020-07-30 20:23:34
【问题描述】:
我试图在一个链表中迭代一个链表,但我不知道如何继续它。我习惯于将传递的参数用于将被迭代的内容,但是当我在链表中迭代链表时,我不知道将与我正在比较的元素匹配的列表。
目前,内部链表“nestedLinkedListIterator”的迭代器正在阻止编译,因为“nestedAlbum”没有相应的参数。我没有提供参数,因为内部 LinkedList“nestedLinkedListIterator”可能会随着外部 Linked 列表的迭代而发生变化,同时使用传递的 title 参数检查到虚拟对象中。
这是我正在尝试做的一个示例
private static boolean addSongFromAlbumToAlbum(LinkedList<Album> albums1, LinkedList<Song> targetAlbum,
String title){
//creating a dummy song for comparison using title parameter with arbitrary time duration.
Song dummySong = new Song(title, 000);
ListIterator<Album> albumsListIterator = albums1.listIterator();
ListIterator<Song> targetAlbumListIterator = targetAlbum.listIterator();
//nested LinkedList iterator (for the song LinkedList is each album being iterated.
ListIterator<Song> nestedLinkedListIterator = nestedAlbum.listIterator();
/*if the "nestedAlbum" is going to change with every iteration of the outer Linked list how can I
* use the nestedAlbum.listIterator with it. normaly I am used to using a parameter tha is passed in
* the place of "nestedAlbum" but I don't think that would work because wither every new album element in "albums1"
* there will be a new song list. correct me if im wrong*/
//checking whether the song with the "title" parameter entered exists in the LinkedList
//of albums
while(albumsListIterator.hasNext()){
while(nestedLinkedListIterator.hasNext()){
//checking if current iteration has an object with same value for title as title parameter.
Song comparisonSongToAdd = nestedLinkedListIterator.next();
int comparisonValue = comparisonSongToAdd.getTitle().compareTo(title);
if(comparisonValue ==0){
//check whether the found object already exists in the album
while (targetAlbumListIterator.hasNext()){
SongComparator comparator = new SongComparator(); //create new comparator object to compare
int comparatorValue = comparator.compare(comparisonSongToAdd, targetAlbumListIterator.next());
if (comparatorValue == 0) {
System.out.println(comparisonSongToAdd + " already exists in the Album. please choose\n a different song.");
return false;
}//end if comparator
}//end target album while
targetAlbumListIterator.add(comparisonSongToAdd);
}//end if song title found
}//end nested album while
}//end albums while iterator
return true;
}//end addSongFromAlbum method
///SongComparator 类
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public int compare(Song song1, Song song2){
if(song1.getTitle() == song2.getTitle() && song1.getDurationSeconds() == song2.getDurationSeconds()){
return 0;
}else{
return -1;
}
}
}
【问题讨论】:
-
基于从您的代码中收集到的一些想法,我认为使用两个谨慎的列表是不正确的。我认为专辑列表需要是列表列表:
LinkedList<List<Songs>> albums -
您的比较器无效,因为它从不返回值
1。
标签: java object linked-list