gpt4 book ai didi

java - 迭代对象的自定义 LinkedList 类

转载 作者:行者123 更新时间:2023-12-01 11:39:09 26 4
gpt4 key购买 nike

我创建了自己的 LinkedList 类,并创建了一个包含对象 Song 的 LinkedList (包含标题、艺术家、专辑、长度)。我遇到的错误是,当尝试迭代列表时,我收到“只能迭代 java.lang.Iterable 数组”。我认为我的问题是我正在迭代类实例,因此在我的链接列表类中缺少一些能够执行此类迭代的内容。但不确定我需要添加什么,提前致谢。

这是我尝试迭代的地方:

System.out.print("Enter song title: ");
String searchTitle = input.nextLine();
for ( Song i : list ){
if ( i.getTitle() == searchTitle ){
System.out.println(i);
found = true;
}
}
if ( found != true ){
System.out.println("Song does not exist.");
}

我的 LinkedList 类

public class LinkedList {

private Node first;

private Node last;

public LinkedList(){
first = null;
last = null;
}

public boolean isEmpty(){
return first == null;
}

public int size(){
int count = 0;
Node p = first;
while( p != null ){
count++;
p = p.getNext();
}
return count;
}

public Node get( int i ){
Node prev = first;
for(int j=1; j<=i; j++){
prev = prev.getNext();
}
return prev;
}

public String toString(){
String str = "";
Node n = first;
while( n != null ){
str = str + n.getValue() + " ";
n = n.getNext();
}
return str;
}

public void add( Song c ){
if( isEmpty() ) {
first = new Node(c);
last = first;
}else{
Node n = new Node(c);
last.setNext(n);
last = n;
}
}

歌曲类

public class Song {

private String title;

private String artist;

private String album;

private String length;

private static int songCounter = 0;

public Song(String title, String artist, String album, String length){
this.title = title;
this.artist = artist;
this.album = album;
this.length = length;
songCounter++;
}

public String getTitle(){
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getArtist(){
return artist;
}

public void setArtist(String artist) {
this.artist = artist;
}

public String getAlbum(){
return album;
}

public void setAlbum(String album){
this.album = album;
}

public String getLength(){
return length;
}

public void setLength(String length){
this.length = length;
}

public static int getSongCounter(){
return songCounter;
}

public int compareArtist(Song o){
return artist.compareTo(o.artist);
}

public int compareTitle(Song o){
return title.compareTo(o.title);
}
@Override
public String toString(){
return title +","+artist+","+album+","+length;
}

最佳答案

错误消息非常明确:

Can only iterate over array of java.lang.Iterable.

这意味着您的类必须实现 Iterable界面。

对于您的情况,必须实现此功能的类必须是 LinkedList:

public class LinkedList implements Iterable<Song> {
//implement methods in Iterable interface
}

您还可以升级您的 LinkedList 实现来处理通用元素,而不仅仅是 Song 对象引用。

关于java - 迭代对象的自定义 LinkedList 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688729/

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