我创建了自己的LinkedList
课程并创建了一个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;
}
答案 0 :(得分:1)
错误消息非常明确:
只能迭代
java.lang.Iterable
的数组。
这意味着您的班级必须实施Iterable
界面。
对于您的情况,必须实现此目的的类必须是LinkedList
:
public class LinkedList implements Iterable<Song> {
//implement methods in Iterable interface
}
您也可以升级您的LinkedList
实现来处理通用元素,而不仅仅是Song
对象引用。