2016-05-21 3 views
1

У меня проблемы с кодом, но я не могу найти его. Моя проблема в том, что значение, которое я сохраняю в массиве, не сохраняется в моем объекте. Код (пожалуйста, обратите внимание, что @Override часть в перспективе() метод, и связанного определения списка в верхней части класса:Значение, не присвоенное байту

private LinkedList<Order> orders = new LinkedList<Order>(); 

      @Override 
      public void handleDelivery(String tag, Envelope env, AMQP.BasicProperties props, byte[] body) 
        throws IOException { 
       byte[] tmp = new byte[5]; 
       tmp[0] = nextID; 
       nextID++; 
       channel.basicPublish("", "toClient", null, new byte[]{tmp[0]}); 
       for (int i = 1; i < tmp.length; i++) 
        tmp[i] = body[i-1]; 
       orders.add(new Order(tmp)); 
       processOrders(tmp); 

Мой класс Order просто

private byte id; 
/** 
* Byte containing the amount of cups of coffee. Amount is represented as a 
* number (Integer) 
*/ 
private byte coffee; 
/** 
* Byte indicating the amount of cafe Latté that has been ordered. Amount 
* is represented as a number (Integer) 
*/ 
private byte cafeLatte; 
/** 
* Byte indicating the amount of smoothies that has been ordered. Amount 
* is represented as a number (Integer) 
* 
*/ 
private byte smoothie; 
/** 
* Byte indicating the amount of Ice coffee that has been ordered. Amount 
* is represented as a number (Integer) 
*/ 
private byte iceCoffee; 
/** 
* Boolean showing if hot drinks has been served or not. 
*/ 
private boolean hotServed; 
/** 
* Boolean showing if cold drinks has been served or not. 
*/ 
private boolean coldServed; 

public Order(byte[] orders) { 
    id = orders[0]; 
    coffee = orders[1]; 
    cafeLatte = orders[2]; 
    smoothie = orders[3]; 
    iceCoffee = orders[4]; 
} 

public byte getId() { 
    return id; 
} 

public boolean coldServed() { 
    return coldServed; 
} 

public void serveCold(boolean coldServed) { 
    this.coldServed = coldServed; 
} 

public void serveHot(boolean served) { 
    hotServed = served; 
} 

public boolean hotServed() { 
    return hotServed; 
} 

/** 
* Method for converting the order into a byte array. 
* @return a 5 columns byte array containing id, coffee, cafe latté, 
* smooties, ice coffees. 
*/ 
public byte[] toByteArray() { 
    return new byte[] {id, coffee, cafeLatte, smoothie, iceCoffee}; 
} 

/** 
* Method for retrieving all the ordered cold drinks with id first. 
* @return An array with numbers indicating the amount of smoothies and 
* Ice coffee to make. Id of the order is first, smoothies next and last 
* Ice coffee. 
*/ 
public byte[] getColdDrinks() { 
    return new byte[] {id, smoothie, iceCoffee}; 
} 

/** 
* Method for retrieving all the ordered hot drinks with id first. 
* @return An array with numbers indicating the amount of coffee and 
* cafelatte to brew. Id of the order is first, coffee next and last 
* cafeLatte. 
*/ 
public byte[] getHotDrinks() { 
    return new byte[] {id, coffee, cafeLatte}; 
} 

При запуске отладки в Eclipse, я вижу, что массив tmp в методе handleDelivery возвращает правильные значения из массива body, а orders.add(new Order(tmp)); добавляет элемент в мой связанныйList, но только со значениями id, 0,0,0,0 (обратите внимание, что id - правильный идентификатор, полученный из rabbitmq), но если я, например закажите чашку кофе, значение 1 теряется, когда я вызываю orders.add(tmp)); как-то.

ответ

0

Объекты не должны быть заданы классом (кроме констант), а конструкторами или методами запуска. Изменение от private LinkedList<Order> orders = new LinkedList<Order>(); в классе до private LinkedList<Order> orders; и добавлено orders = new LinkedList<Order>(); в run() решило проблему.

+0

«Объекты не должны быть заданы классом, а конструкторами или методами запуска». Откуда у тебя это? Совершенно нормально создавать объекты на уровне класса. Не могли бы вы объяснить, почему перемещение инициализации на 'run'-method решает проблему? – Turing85

+0

Нет, я не могу объяснить, почему, но поскольку я решил проблему, сделав это изменение, я вижу, что есть разница, хотя я не знаю, что – Zuenonentu

Смежные вопросы