【问题标题】:Iteration and checking element of an LinkedList of a LinkedListLinkedList 的 LinkedList 的迭代和检查元素
【发布时间】: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&lt;List&lt;Songs&gt;&gt; albums
  • 您的比较器无效,因为它从不返回值1

标签: java object linked-list


【解决方案1】:

我没有完全理解你试图用你的代码实现什么,但我会尝试从@markspace 的观察开始回答你的问题。

所以我假设您正在尝试遍历专辑列表:albums1,并将与给定 title 匹配的所有歌曲保存在 targetAlbum 变量中。

你的代码有很多地方可以改进:

  • 变量dummySong 是多余的
  • 使用迭代器会使代码更难阅读,尝试使用 for 循环
  • 比较器不能用于自然排序歌曲(不能比较2首不同标题的歌曲),所以最好使用equals()方法

这是一种应该涵盖您在帖子中要求的方法:


private static boolean addSongFromAlbumToAlbum(LinkedList<LinkedList<Song>> albums, LinkedList<Song> targetAlbum, String title) {

    ListIterator<LinkedList<Song>> albumsListIterator = albums.listIterator();
    ListIterator<Song> targetAlbumListIterator = targetAlbum.listIterator();
    ListIterator<Song> albumSongListIterator;

    while(albumsListIterator.hasNext()) {
        
        LinkedList<Song> currentAlbumSongs = albumsListIterator.next();
        albumSongListIterator = currentAlbumSongs.listIterator();

        while(albumSongListIterator.hasNext()) {

            Song comparisonSongToAdd = albumSongListIterator.next();
            boolean songMatchFound = comparisonSongToAdd.getTitle().equals(title);
            
            if(songMatchFound){

                while (targetAlbumListIterator.hasNext()) {
                    
                    Song currentTargetAlbumSong = targetAlbumListIterator.next();
                    
                    if (currentTargetAlbumSong.equals(comparisonSongToAdd)) {
                        System.out.println(comparisonSongToAdd + " already exists in the Album. please choose\n a different song.");
                        return false;
                    }
                }
                targetAlbumListIterator.add(comparisonSongToAdd);
            }
        }
    }
    return true;
}

下面是一个演示程序,涵盖:

  • 测试程序的主函数
  • 我对专辑和歌曲的解读
  • Song 类的 equals 方法
  • 一种重构方法,涵盖我的上述观点

public class HelloWorld {

     public static void main(String []args) {
         
        LinkedList<Song> greenDayAlbum = new LinkedList<>();
        
        greenDayAlbum.add(new Song("21 Guns", 3));
        greenDayAlbum.add(new Song("Basket Case", 3));
        greenDayAlbum.add(new Song("American Idiot", 3));
        
        LinkedList<Song> linkinParkAlbum = new LinkedList<>();
        
        linkinParkAlbum.add(new Song("Numb", 3));
        linkinParkAlbum.add(new Song("In the end", 3));
        linkinParkAlbum.add(new Song("Castle of glass", 3));
        
        LinkedList<LinkedList<Song>> albums = new LinkedList<>();
        albums.add(greenDayAlbum);
        albums.add(linkinParkAlbum);
        
        LinkedList<Song> targetAlbum = new LinkedList<>();
         
        //addSongFromAlbumToAlbum(albums, targetAlbum, "Basket Case");
        findMatchedSongs(albums, targetAlbum, "Basket Case");
        
        for(Song matchedSong : targetAlbum) {
            System.out.println(matchedSong); //outputs Song[title=Basket Case, duration=3]
        }
     }
    
    private static boolean findMatchedSongs(LinkedList<LinkedList<Song>> inputAlbums, LinkedList<Song> outputAlbum, String searchedTitle) {
        
        if (searchedTitle == null) {
            System.out.println("Provide a title to search for.");
            return false;
        }
        
        for (LinkedList<Song> songs : inputAlbums) {
            for (Song song : songs) {
                if (!searchedTitle.equals(song.getTitle())) {
                    continue;
                }
                if (outputAlbum.contains(song)) {
                    System.out.println(String.format("Song %s already exists in the album; please choose a different song", song.getTitle()));
                    return false;
                }
                
                outputAlbum.add(song);
            }
        }
        return true;
    }
}


class Album {
    
    private Collection<Song> songs;
    
    public Album(Collection<Song> songs) {
        this.songs = songs;
    }
    
}

class Song {
    
    String title;
    int duration;
    
    Song(String a, int b) {
        this.title = a;
        this. duration = b;
    }
    
    public String getTitle() {
        return title;
    }
    
    public int getDurationSeconds() {
        return duration;
    }
    
    @Override
    public boolean equals(Object that) {
        
        if (that == null) {
            return false;
        }
        
        if (!(that instanceof Song)) {
            return false;
        }
        
        Song song = (Song) that;
        
        if (this.title != null && !this.title.equals(song.getTitle())) {
            return false;
        }
        
        if (this.duration != song.getDurationSeconds()) {
            return false;
        }
        
        return true;
    }

    //hashCode() function omitted for brevity
    
    @Override
    public String toString() {
        return String.format("Song[title=%s, duration=%d]", title, duration);
    }
    
}

【讨论】:

  • 谢谢,这正是我想要做的。对不起,误解。我会试一试,让你知道
猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2012-05-08
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多