[英]LinkedList inside a LinkedList iteration in java
我試圖在鏈接列表中迭代鏈接列表,但我不確定如何進行。 我習慣於將傳遞的參數用於將要迭代的內容,但是當我在鏈表中迭代鏈表並計划迭代時,直到我找到與傳遞的虛擬 object 匹配的記錄。
這是我正在嘗試做的一個例子
private static boolean addSongFromAlbumToAlbum(LinkedList<Album> albums1, LinkedList<Song> targetAlbum,
String title){
//creating a dummy song for comparison of title parameter with arbitrary time duration.
Song dummySong = new Song(title, 000);
ListIterator<Album> album1ListIterator = albums1.listIterator();
ListIterator<Song> targetAlbumListIterator = targetAlbum.listIterator();
//nested album iterator
ListIterator<Song> nestedAlbumInAlbum = nestedAlbum.listIterator();
//checking whether the song with the "title" parameter entered exists in the LinkedList
//of albums
while(album1ListIterator.hasNext()){
while(nestedAlbumInAlbum.hasNext()){
//checking if current iteration has an object with same value for title as title parameter.
Song comparisonSongToAdd = nestedAlbumInAlbum.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 class
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 中迭代 LinkedList? 如果它需要一個參數,我應該如何確定該參數使用什么,因為它會隨着外部 while 循環的每次迭代而改變。
您可以使用 java 8 個流,而不是創建迭代器,
為了找到相冊 1 和相冊 2 中的內容,請使用:
albums1.forEach(album1Element -> {
//keeps only what returns true in the filter.
List<Song> listOfSongsToAdd = targetAlbum.filter(song -> song.compareTo(title)).collect(Collectors.toList);
listOfSongsToAdd.forEach(songToAdd -> {
...
});
});
檢查下面的代碼行。 在這里, next()
返回一Song
object, title
是一個String
object。這兩者無法比較。 您可能必須調用nestedAlbumInAlbum.next()
並將 object 存儲在Song
引用變量中,然后將song.getTitle()
與title
進行比較。
int comparisonValue = nestedAlbumInAlbum.next().compareTo(title);
此外,您多次調用nestedAlbumInAlbum.next()
。 1 個實例在上面,另一個實例在if
條件內。 您應該限制只調用next()
方法進行迭代。 每次調用nestedAlbumInAlbum.next()
時,它都會返回下一Song
object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.