如何按字母顺序插入字符串的ArrayList

时间:2016-11-02 03:41:11

标签: java arraylist

所以在类锦标赛中,我有一个包含的ArrayList(String Name,int disap)

有一种方法alphabeticSort()可按名称的字母顺序对播放器列表进行排序。我必须使用插入排序。

下面我尝试调整我知道的插入排序算法,使其工作但

两行
players.add(j+1) 

给我一​​个错误说"作业的左侧必须是一个变量。"我理解这意味着什么,但我无法为它找到解决方案。

    public void alphabeticSort() {

    for(int i = 1; i < players.size(); i++)  {
        String key = players.get(i).getName();
        int j = i - 1;
        while (j >= 0 && key.compareTo(players.get(i).getName()) < 0) {
            players.add(j+1) = players.get(j);

            j--;
        }
        players.add(j+1) = key;
    }

我不知道如何解决这个问题。我是否走在正确的轨道上?请帮忙。任何帮助表示赞赏

编辑:我已经改变了

的第一个实例
players.add(j+1) = players.get(j);

players.set(j+1, players.get(j));

我是否对第二个实例(最后一行)做同样的事情

我也发现了这行

 while (j >= 0 && key.compareTo(players.get(i).getName()) < 0)

是错误的,因为实际的插入排序应该是

 while(j >= 0 && arr[k]> backup)

但我不知道如何使用字符串来实现它,因为你不能在字符串上使用运算符。 HELP ???

编辑2:

JUnit测试应该测试它是否有效

public void testAlphabeticSort() {
    int [] par = {3,4,5,4,5,3,4,3,5,3,4,5,4,3,4,5,4,3};
    int [] scores1 = {3,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,4};
    int [] scores2 = {4,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,4};
    int [] scores3 = {3,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,5};
    Tournament T = new Tournament(par);
    T.enter("Scott",  1, scores3);
    T.enter("Norman",  2, scores1);
    T.enter("Palmer",  4, scores2);
    T.alphabeticSort();
    ArrayList<Player> sortedPlayers = T.getPlayers();
    Player player1 = new Player("Norman", 2, scores1);
    Player player2 = new Player("Palmer", 4, scores2);
    Player player3 = new Player("Scott", 1, scores3);
    assertTrue(sortedPlayers.get(0).equals(player1));
    assertTrue(sortedPlayers.get(1).equals(player2));
    assertTrue(sortedPlayers.get(2).equals(player3));
}

5 个答案:

答案 0 :(得分:2)

我认为你应该考虑一些关于List s

的观点
  1. ArrayList<E>用于允许快速随机读取访问
  2. LinkedList<E>允许定时插入或移除。
  3. 如果您的程序有很多插入和删除,那么您应该考虑使用LinkedList代替ArrayList

    还会看到:similar

    代码中的问题是players.add(j+1) = players.get(j);。您只能对变量使用赋值运算符而不能使用方法。

    但是,如果您愿意设置j+1 List的{​​{1}}值,那么您可以使用players方法,该方法可用于set() LinkedList 1}}和ArrayList

    players.set(j+1, players.get(j));
    

答案 1 :(得分:0)

对于特定错误,您的行应修改为:

players.add(j+1, players.get(j));

它将移动列表中的后续元素。

如果使用set函数,它将替换索引j + 1

处的实体

观察更改并更改功能体,如下所示:

for(int i = 1; i < players.size(); i++)  {
    Player key = players.get(i);
    int j = i - 1;
    while (j >= 0 && key.getName().compareTo(players.get(j).getName()) < 0) {
        players.set(j+1, players.get(j));

        j--;
    }
    players.set(j+1, key);
}

答案 2 :(得分:0)

你错了:players.add(j+1) = players.get(j);

您无法为方法指定值。

ArrayList提供了两种添加Object的方法。

在你的情况下:你使用add(Object) - 它会在最后一个位置将参数中的Object添加到ArrayList中并返回true或false。

解决您的问题:让我们使用方法add(int index,Object object)。此方法将Object插入到具有索引位置的ArrayList中。

代码xample:

  

players.add(j + 1,players.get(j));

答案 3 :(得分:0)

你也可以实现自己的比较器以保持清洁,我制作了一个小程序,以便你可以轻松测试

播放器:

public class Player
{
    private String name;
    private int handicap;

    public Player (String name, int handicap)
    {
        this.name = name;
        this.handicap = handicap;
    }
    /**
     * @return the name
     */
    public String getName ( )
    {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName ( String name )
    {
        this.name = name;
    }
    /**
     * @return the handicap
     */
    public int getHandicap ( )
    {
        return handicap;
    }
    /**
     * @param handicap the handicap to set
     */
    public void setHandicap ( int handicap )
    {
        this.handicap = handicap;
    }
}

ComparatorPlayer:

import java.util.Comparator;

public class ComparatorPlayer implements Comparator<Player> {

    @Override
    public int compare(Player p1, Player p2)
    {
        if( p1.getName ( ).compareTo ( p2.getName ( ) ) < 0 )
        {
            return -1;
        }
        else if ( p1.getName ( ).compareTo ( p2.getName ( ) ) > 0 )
        {
            return 1;
        }
        return 0;
    }


}

用于测试目的的控制台:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Console
{

    public static void main ( String [ ] args )
    {
        List < Player > players = new ArrayList< Player >();
        List < Player > playersOrdered = new ArrayList < Player > ( );

        players.add ( new Player ( "Chris", 32222 ) );
        players.add ( new Player ( "John", 3 ) );
        players.add ( new Player ( "Zebra", 5 ) );
        players.add ( new Player ( "Albert", 333 ) );
        players.add ( new Player ( "Chris", 32222 ) );
        players.add ( new Player ( "Chris", 3 ) );



        Collections.sort ( players, new ComparatorPlayer ( ) );



        for ( Player player : players )
        {
            System.out.println ( player.getName ( ) +  " + " + player.getHandicap ( ) );
            playersOrdered.add ( player );
        }

    }

}

输出:

Albert + 333

Chris + 32222

Chris + 32222

Chris + 3

John + 3

Zebra + 5

参考文献:

Comparator

编辑:

对不起,我没有意识到你必须实现自己的排序功能。试试这个:

控制台&amp;&amp; alphabeticSort:

import java.util.ArrayList;

public class Console
{

    public static void main ( String [ ] args )
    {
        System.out.println ( "Starting" );
        ArrayList < Player > players = new ArrayList < Player > ( );
        players.add ( new Player ( "John" , 3 ) );
        players.add ( new Player ( "Chris" , 32222 ) );
        players.add ( new Player ( "Zebra" , 5 ) );
        players.add ( new Player ( "Albert" , 333 ) );
        players.add ( new Player ( "Christ" , 32222 ) );
        players.add ( new Player ( "Chris" , 3 ) );

        alphabeticSort ( players );

        for ( Player player : players )
        {
            System.out.println ( player.getName ( ) + " + " + player.getHandicap ( ) );
        }

        System.out.println ( "Finish" );
    }

    // alphabeticSort pass by parameter
    public static void  alphabeticSort ( ArrayList < Player > players )
    {
        int i = 1 , j;
        Player key = new Player ( );
        ArrayList < Player > inputArray = players;

        for ( j = 1 ; j < inputArray.size ( ) ; j ++ )
        {
            key = inputArray.get ( j );
            i = j - 1;

            while ( i >= 0 )
            {
                if ( key.getName ( ).compareTo ( inputArray.get ( i ).getName ( ) ) > 0 )
                {
                    break;
                }

                Player element = inputArray.get ( i + 1 );
                inputArray.set ( i + 1 , inputArray.get ( i ) );
                inputArray.set ( i , element );
                i -- ;
            }
        }
    }
}

输出:

启动

Albert + 333

Chris + 3

Chris + 32222

基督+ 32222

John + 3

Zebra + 5

完成

OP提出的EDIT2解决方案:

这是您的解决方案(通过JUnit测试)

播放器:

import java.util.Arrays;

public class Player
{
    private String name;
    private int handicap;
    private int scores[];

    public Player( )
    {

    }

    public Player (String name, int handicap)
    {
        this.name = name;
        this.handicap = handicap;
    }

    public Player (String name, int handicap, int [] scores)
    {
        this.name = name;
        this.handicap = handicap;
        this.setScores ( scores ); 
    }

    /**
     * @return the name
     */
    public String getName ( )
    {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName ( String name )
    {
        this.name = name;
    }
    /**
     * @return the handicap
     */
    public int getHandicap ( )
    {
        return handicap;
    }
    /**
     * @param handicap the handicap to set
     */
    public void setHandicap ( int handicap )
    {
        this.handicap = handicap;
    }

    /**
     * @return the scores
     */
    public int [] getScores ( )
    {
        return scores;
    }

    /**
     * @param scores the scores to set
     */
    public void setScores ( int scores[] )
    {
        this.scores = scores;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode ( )
    {
        // TODO Auto-generated method stub
        return super.hashCode ( );
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals ( Object obj )
    {
        Player objToCompare = (Player) obj;
        if( this.handicap == objToCompare.getHandicap ( ) &&
                this.name.equals ( objToCompare.getName ( ) ) &&
                    Arrays.equals ( this.scores , objToCompare.scores ))
        {
            return true;
        }
        return false;

    }

}

赛:

import java.util.ArrayList;

public class Tournament
{

    int [] scores;
    ArrayList<Player> players = new ArrayList<Player> ( );
    int [] pars;

    public Tournament ( int [ ] par )
    {
        this.pars = par;
    }

    /**
     * @return the scores
     */
    public int [ ] getScores ( )
    {
        return scores;
    }

    /**
     * @param scores the scores to set
     */
    public void setScores ( int [ ] scores )
    {
        this.scores = scores;
    }

    /**
     * @return the players
     */
    public ArrayList < Player > getPlayers ( )
    {
        return players;
    }

    /**
     * @param players the players to set
     */
    public void setPlayers ( ArrayList < Player > players )
    {
        this.players = players;
    }

    /**
     * @return the pars
     */
    public int [ ] getPars ( )
    {
        return pars;
    }

    /**
     * @param pars the pars to set
     */
    public void setPars ( int [ ] pars )
    {
        this.pars = pars;
    }

    /**
     * Enter a player to a tournament
     * @param name
     * @param handicap
     * @param scores
     */
    public void enter ( String name , int handicap , int [ ] scores )
    {
        this.players.add ( new Player ( name, handicap, scores ));
    }


    /**
     * alphabeticSort by player name
     */
    public void alphabeticSort ()
    {
        int i = 1 , j;
        Player key = new Player ( );
        ArrayList < Player > inputArray = this.getPlayers ( );

        for ( j = 1 ; j < inputArray.size ( ) ; j ++ )
        {
            key = inputArray.get ( j );
            i = j - 1;

            while ( i >= 0 )
            {
                if ( key.getName ( ).compareTo ( inputArray.get ( i ).getName ( ) ) > 0 )
                {
                    break;
                }

                Player element = inputArray.get ( i + 1 );
                inputArray.set ( i + 1 , inputArray.get ( i ) );
                inputArray.set ( i , element );
                i -- ;
            }
        }
       this.players = inputArray;
    }

}

JUnit的:

enter image description here

答案 4 :(得分:0)

在上面的代码中,您始终将i的值与自身进行比较。将其更改为j,最后一个语句应为players.set(j+1,key);

所以最终的代码看起来像这样。

 for(int i = 1; i < players.size(); i++)  {
    String key = players.get(i).getName();
    int j = i - 1;
    while (j >= 0 && key.compareTo(players.get(j).getName()) < 0) {
        players.set(j+1, players.get(j));

        j--;
    }
      players.set(j+1,key);