ArrayList组合为一个字符串

时间:2015-05-04 05:42:01

标签: java arraylist tostring

更新:

package packet;

import java.util.ArrayList;   //java library implementation of List interface
import java.util.Arrays;
import java.util.List;            //java library the List interface
import java.util.Random;    //for random number generator
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
private String message;
private int packetLength;
private List<Packet> dividedMessage;    //use java library java.util.List 
private boolean messageSent;
private Random generator;                      //use java library java.util.Random


public Message(String theMessage, int thePacketLength)
       {
        message = theMessage;
        packetLength = thePacketLength;
        receiveInFile(message);


       }

public void send()
{          // divide the message into Packet and store the packets in the list   
                  // dividedMessage
    dividedMessage = new ArrayList<Packet>();

    List<String> items = Arrays.asList(message.split("\\s*,\\s*"));
    int sequenceNumber = packetLength;
    String nextPiece = message;
                //This is the line of code to create a Packet object using a sequence   
                   //number and a string (represent part of the message)
    Packet nextPacket = new Packet(sequenceNumber, nextPiece);
    dividedMessage.add(nextPacket);

        }
/** Simulates the receipt of the packets of a message. The packets
         are not in any particular order and are written to a text file.
            @param fileName  a string that names the file to be created and the    
                                           packets are written to the file.
            @return true if the packets are received, or
                          false if the message was never sent or the file
                          cannot be created */


public boolean receiveInFile(String fileName)
{

    String[] items = message.split(" ");
    int numberOfPackets = items.length;
   dividedMessage = Arrays.asList(message.split(","));

    shuffle(dividedMessage, numberOfPackets);
   // container.send();

    return messageSent;

       }
public String toString()
       {
        return message;

       }
private void shuffle (List<Packet>  packetList, int  numberOfPackets)
{
        if (numberOfPackets > 1)
        {
               // swap packet at index numberOfPackets - 1 and a random index
               Packet temp = packetList.get(numberOfPackets - 1);
               int randomIndex = Math.abs(generator.nextInt()) 
               %numberOfPackets;
               packetList.set(numberOfPackets - 1, packetList.get(randomIndex));
               packetList.set(randomIndex, temp);
               shuffle(packetList, numberOfPackets - 1);
        }  // end if
      }  // end Shuffle
}// end class Message

原件:

我正在制作一个示例程序,目的是无序地发送数据包并重新排序然后以完整字符串输出数据包。我有订购部分工作正常,所以我没有包括它们,我似乎不知道从这里下一步去哪些,这些类应该采取重新排序的数据包,并使它们成为一个字符串。任何帮助都很棒!

public class Packet implements Comparable<Packet>
{
    private int    sequence;      //sequence number of the packet
    private String message;    //a part of the message represented by the packet
    public Packet(int sequenceNumber, String nextPiece) {
        setSequence(sequenceNumber);
        setMessage(nextPiece);
        Message test = new Message(message, sequence);

    }
    @Override
    public int compareTo(Packet o) {
        int comparedSize = o.sequence;
        if (this.sequence > comparedSize) {
            return 1;
        } else if (this.sequence == comparedSize) {
            return 0;
        } else {
            return -1;
        }

    }
    public String toString() {
        return message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public int getSequence() {
        return sequence;
    }
    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    //Implement constructor and other methods as necessary
}
import java.util.ArrayList;   //java library implementation of List interface
import java.util.List;            //java library the List interface
import java.util.Random;    //for random number generator
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
    private String message;
    private int packetLength;
    private List<Packet> dividedMessage;    //use java library java.util.List
    private boolean messageSent;
    private Random generator;                      //use java library java.util.Random

    /**implement constructor  */
    public Message(String theMessage, int thePacketLength)
    {
        message = theMessage;
        packetLength = thePacketLength;

    }
    /** Sends this message as a sequence of packets. */
    public void send()
    {          // divide the message into Packet and store the packets in the list
        // dividedMessage
        dividedMessage = new ArrayList<Packet>();
        int sequenceNumber = 0;
        String nextPiece = null;
        //This is the line of code to create a Packet object using a sequence
        //number and a string (represent part of the message)
        Packet nextPacket = new Packet(sequenceNumber, nextPiece);

    }
    /** Simulates the receipt of the packets of a message. The packets
     are not in any particular order and are written to a text file.
     @param fileName  a string that names the file to be created and the
     packets are written to the file.
     @return true if the packets are received, or
     false if the message was never sent or the file
     cannot be created
     */
    public boolean receiveInFile(String fileName)
    {

        // shuffle the packets to simulate their arrival order
        int numberOfPackets = 0;
        shuffle(dividedMessage, numberOfPackets);
        return messageSent;

    }
    public String toString()
    {
        return message;

    }
    private void shuffle (List<Packet>  packetList, int  numberOfPackets)
    {
        if (numberOfPackets > 1)
        {
            // swap packet at index numberOfPackets - 1 and a random index
            Packet temp = packetList.get(numberOfPackets - 1);
            int randomIndex = Math.abs(generator.nextInt())
                              %numberOfPackets;
            packetList.set(numberOfPackets - 1, packetList.get(randomIndex));
            packetList.set(randomIndex, temp);
            shuffle(packetList, numberOfPackets - 1);
        }  // end if
    }  // end Shuffle
}// end class Message

最初的信息是“在工会的6点见我。”

收到的消息包: 1 Mee 3 e 6 clo 5点' 4吨6 2吨 11离子 7 ck 8英寸 10联合国 9

收到的消息是“在工会6点见我”

3 个答案:

答案 0 :(得分:1)

为什么不对ArrayList本身的Packets进行排序,因为您已经实现了Comparable接口?你可以

  1. 对数据包列表进行排序。您可以使用Collections.sort()
  2. 遍历排序列表,从列表中获取下一个项目并将其nextPiece附加到字符串。
  3. 此后你应该有正确的字符串。

答案 1 :(得分:0)

在这里,我可以给你一些提示,但尝试自己编写代码。

首先,使用split(" ")String 1 Mee 3 e a 6 clo 5 o' 4 t 6 2 t m 11 ion 7 ck 8 in 10 un 9 the拆分为String[]

假设数字和字符串块交替出现,将它们放入Map<Integer, String>。如果您不想进一步排序,可以使用TreeMap

最后,遍历Map中的值。将它们添加到StringBuilder,最后使用toString()获取String实例,这应该是结果。

修改:如果Packet implements Comparable<Packet>TreeSet将为您执行所有排序(因为不会有任何相等的Packet)。请参阅以下代码(为方便起见,将其简化并压缩为单个java文件)。

import java.util.*;
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
    private String message;
    private int packetLength;
    private List<Packet> dividedMessage;    //use java library java.util.List 
    private boolean messageSent;
    private Random generator;                      //use java library java.util.Random
    public Message(String theMessage, int thePacketLength)
    {
        message = theMessage;
        packetLength = thePacketLength;
        //receiveInFile(message);
    }

    public static void main(String[] args)
    {
        ArrayList<Packet> list = new ArrayList<>();
        list.add(new Packet(1, "Mee"));
        list.add(new Packet(3, "e a"));
        list.add(new Packet(6, "clo"));
        list.add(new Packet(5, "o\'"));
        list.add(new Packet(4, "t 6 "));
        list.add(new Packet(2, "t m"));
        list.add(new Packet(11, "ion"));
        list.add(new Packet(7, "ck "));
        list.add(new Packet(8, "in "));
        list.add(new Packet(10, "un"));
        list.add(new Packet(9, "the "));
        Collections.shuffle(list);
        /*
         * now shuffled
         * read message
         */
        TreeSet<Packet> set = new TreeSet<>(list);
        StringBuilder builder = new StringBuilder();
        for (Packet p: set)
        {
            builder.append(p.getMessage());
        }
        System.out.println(builder.toString());
    }

    public String toString()
    {
        return message;
    }

    static class Packet implements Comparable<Packet>
    {
        private int    sequence;   //sequence number of the packet
        private String message;    //a part of the message represented by the packet
        public Packet(int sequenceNumber, String nextPiece) {
            setSequence(sequenceNumber);
            setMessage(nextPiece);
            Message test = new Message(message, sequence);
        }
        @Override
        public int compareTo(Packet o) {
            int comparedSize = o.sequence;
            if (this.sequence > comparedSize) {
                return 1;
            } else if (this.sequence == comparedSize) {
                return 0;
            } else {
                return -1;
            }

        }
        public String toString() {
            return message;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        public int getSequence() {
            return sequence;
        }
        public void setSequence(int sequence) {
            this.sequence = sequence;
        }
    }
}

IMO,SetList更方便,因为没有相同的元素。如果订单不重要,请使用HashSet;如果订单必须不变,则使用LinkedHashSet;如果需要自然排序,则使用TreeSet

答案 2 :(得分:0)

我尝试了以下代码,它运行正常:

public static void main(String[] args) {
    List<Packet> dividedMessage = new ArrayList<>();
    dividedMessage.add(new Packet(1, "Mee"));
    dividedMessage.add(new Packet(2, "t m"));
    dividedMessage.add(new Packet(3, "e a"));
    dividedMessage.add(new Packet(6, "clo"));
    dividedMessage.add(new Packet(5, "o'"));
    dividedMessage.add(new Packet(4, "t 6 "));
    dividedMessage.add(new Packet(11, "ion"));
    dividedMessage.add(new Packet(7, "ck"));
    dividedMessage.add(new Packet(8, " in"));
    dividedMessage.add(new Packet(10, " un"));
    dividedMessage.add(new Packet(9, " the"));

    Collections.sort(dividedMessage);
    String originalMessage = "";
    for (Packet packet : dividedMessage)
    {
        originalMessage += packet.getMessage();
    }
    System.out.println(originalMessage);
}

我希望这就是你想要的。输出为:Meet me at 6 o'clock in the union

如果你有很多数据包,那么性能可能是一个问题,你可以使用StringBuilder:

StringBuilder sb = new StringBuilder();
for (Packet packet : dividedMessage)
{
    sb.append(packet.getMessage());
}