【发布时间】:2015-04-17 01:35:43
【问题描述】:
我创建了自己的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.");
}
我的链表类
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;
}
【问题讨论】:
-
发布您的
Song课程。 -
@Jean-François Savard 添加了歌曲类
标签: java linked-list iteration