Функция addLast LinkedList заменяет другие значения в списке - PullRequest
0 голосов
/ 14 апреля 2020

В настоящее время я работаю над созданием очереди для отправки пакетов данных. однако я столкнулся с проблемой, когда при использовании функции addLast в моем LinkedList она заменяет каждую пару в списке на добавляемую в нее пару.

очередь:

private LinkedList<Pair<Integer, ByteBuffer>> queue;

Pair было импортировано из javafx.util.Pair;

Инициализация очереди:

queue = new LinkedList<>();

Метод:

    public synchronized void addToQueue(int bytes, ByteBuffer data) {
        Pair<Integer, ByteBuffer> local = new Pair(bytes, data);
        queue.addLast(new Pair(bytes, data));

        if(bytes>2){
            int i = 0;
            for(Pair<Integer,ByteBuffer> datas:queue ){
                System.out.println("\n Data in the "+i+ "th position in queue is: ");
                printByteBufferAsBytes(datas.getValue(), datas.getKey());
                i++;
            }
        }

    }

В Для отладки я печатал data всякий раз, когда отправляется пакет данных. Этот метод также доступен для отправки меньших пакетов, однако он работает должным образом для меньших пакетов.

После выполнения кода выводятся следующие результаты:

Data in the 0th position in queue is: 
1 5 40 -128 -58 0 0 42 111 34 -24 0 0 0 0 112 114 105 110 116 66 121 116 101 66 117 102 102 101 114 65 115 something was added to queue

 Data in the 0th position in queue is: 
2 5 40 -128 -58 17 0 115 -86 119 76 66 121 116 101 115 40 113 117 101 117 101 46 112 101 101 107 40 41 46 103 101 
 Data in the 1th position in queue is: 
2 5 40 -128 -58 17 0 115 -86 119 76 66 121 116 101 115 40 113 117 101 117 101 46 112 101 101 107 40 41 46 103 101 something was added to queue

 Data in the 0th position in queue is: 
2 5 40 -128 -58 38 0 -102 -46 -61 99 116 86 97 108 117 101 40 41 44 32 113 117 101 117 101 46 112 101 101 107 40 
 Data in the 1th position in queue is: 
2 5 40 -128 -58 38 0 -102 -46 -61 99 116 86 97 108 117 101 40 41 44 32 113 117 101 117 101 46 112 101 101 107 40 
 Data in the 2th position in queue is: 
2 5 40 -128 -58 38 0 -102 -46 -61 99 116 86 97 108 117 101 40 41 44 32 113 117 101 117 101 46 112 101 101 107 40 something was added to queue

 Data in the 0th position in queue is: 
3 5 40 -128 -58 59 0 109 60 120 12 11 41 46 103 101 116 75 101 121 40 41 41 101 117 101 46 112 101 101 107 40 
 Data in the 1th position in queue is: 
3 5 40 -128 -58 59 0 109 60 120 12 11 41 46 103 101 116 75 101 121 40 41 41 101 117 101 46 112 101 101 107 40 
 Data in the 2th position in queue is: 
3 5 40 -128 -58 59 0 109 60 120 12 11 41 46 103 101 116 75 101 121 40 41 41 101 117 101 46 112 101 101 107 40 
 Data in the 3th position in queue is: 
3 5 40 -128 -58 59 0 109 60 120 12 11 41 46 103 101 116 75 101 121 40 41 41 101 117 101 46 112 101 101 107 40

Кажется, что каждый раз, когда что-то добавляется в очередь все остальные значения в очереди установлены на то же значение. Если кто-то знает причину этого, я был бы очень признателен за любые указатели.

Метод printByteBufferAsBytes:

    public void printByteBufferAsBytes(ByteBuffer bytes, int bytesLength) {
        for (int i = 0; i < bytesLength; i++) {
            System.out.print(Byte.toString(bytes.get(i)) + " ");
        }
    }

Ответы [ 2 ]

1 голос
/ 14 апреля 2020

В методе addToQueue вам необходимо скопировать содержимое обновленного ByteBuffer в новый байтовый массив:

    public synchronized void addToQueue(int bytes, ByteBuffer data) {
        byte[] copy = Arrays.copyOf(data.array(), bytes);

        Pair<Integer, ByteBuffer> local = new Pair<>(bytes, ByteBuffer.wrap(copy));
        queue.addLast(local);
    // ... the rest of the method remains as is

   }
0 голосов
/ 14 апреля 2020

Реализация addLast () в LinkedList (в Java) выглядит следующим образом:

 public void addLast(AnyType item)
   {
      if( head == null)
         addFirst(item);
      else
      {
         Node<AnyType> tmp = head;
         while(tmp.next != null) tmp = tmp.next;

         tmp.next = new Node<AnyType>(item, null);
      }
   }

Существует реализация Очередь в Java, я бы порекомендовал используйте его вместо LinkedList. Кроме того, методы dequeue и enqueue должны использоваться, чтобы следовать терминологии.

Методы enqueue () и dequeue () в очереди (в Java) определены следующим образом:

public void enqueue(Item item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else           oldlast.next = last;
        n++;
        assert check();
    }

public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = first.item;
        first = first.next;
        n--;
        if (isEmpty()) last = null;   // to avoid loitering
        assert check();
        return item;
    }

Небольшое примечание к LinkedLists, метод add () эквивалентен addLast ().

...