[英]Need help on Index out of bounds exception on arraylist
這就是我的代碼。 當我運行測試時,它給我索引超出范圍錯誤,並且如果
(songList.get(j).getDuration()<(songList.get(j-1).getDuration()) )
{
代碼的一部分。 我該如何解決??? 導入java.util.ArrayList;
/**
* Write a description of class SongList here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class SongList
{
private ArrayList <Song> songList;
/**
* Constructor for objects of class SongList
*/
public SongList()
{
songList = new ArrayList<Song>();
}
public boolean addSong(Song s)
{
songList.add(s);
return true;
}
public int findSong(String title)
{
for (int i=0; i < songList.size(); ++i)
{
if ( songList.get(i).getTitle().compareTo(title) == 0)
return i;
}
return -1 ;
}
public void swapSong(int i, int j)
{
Song[ ] ai = new Song [100];
Song temp = ai[i];
ai[i] = ai[j];
ai[j] = temp;
}
public void sortByDuration()
{
for(int i=0; i < songList.size()-1; ++i)
{
for (int j = songList.size()-1; j > i ; ++j)
{
if (songList.get(j).getDuration()<(songList.get(j-1).getDuration()) )
{
swapSong(j,j-1);
}
}
}
}
public void sortByWriter()
{
for(int i=0; i < songList.size()-1; ++i)
{
for (int j = songList.size()-1; j > i ; --j)
{
if( songList.get(j).getWriter().compareTo(songList.get(j-i).getWriter())<0)
{
swapSong(j,j-1);
}
}
}
}
public void sortByGenre()
{
for(int i=0; i < songList.size()-1; ++i)
{
for (int j = songList.size()-1; j > i ; --j)
{
if (songList.get(j).getGenre().compareTo(songList.get(j-1).getGenre())<0)
swapSong(j,j-1);
}
}}
public void sortByYear()
{
for(int i=0; i < songList.size()-1; ++i)
{
for (int j = songList.size()-1; j > i ; --j)
{
if (songList.get(j).getYear()<(songList.get(j-1).getYear()))
swapSong(j,j-1);
}
}}
public int getSize()
{
return songList.size();
}
}
您正在嘗試使用j
for
循環從ArrayList
的末尾開始。
for (int j = songList.size()-1; j > i ; ++j)
但是,這會增加j
因此您需要使用ArrayList
的末尾。
而是減少j
,這樣您就不會跑到盡頭,因此循環最終將使j
遇到i
並終止:
// HERE
for (int j = songList.size()-1; j > i ; --j)
您的其他j
for
循環已經正確執行--j
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.