繁体   English   中英

需要有关arraylist的索引越界异常的帮助

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM