0

I got this class, but I can't understand how does remove function work. Why it needs to be a class name (Customer) before remove(), and what does it mean Customer customer = (Customer) customers.firstElement();

Can you help me?

private java.util.Vector customers = new java.util.Vector();
Server server;

void insert(AbstractEvent customer){
    customers.addElement(customer);
}
/**
 * @return the first customer in the queue
 */
Customer remove() {
    Customer customer = (Customer) customers.firstElement();
    customers.removeElementAt(0);
          return customer;
}
int size() {
    return customers.size();
}
Winter Soldier
  • 2,607
  • 3
  • 14
  • 18

1 Answers1

2
Customer remove()

The remove() method returns an object of type Customer. That's what the class name before remove() means.

Customer customer = (Customer) customers.firstElement();

customers.firstElement() returns the first element of the Vector object referred by the customers variable. Since the type of customers is a raw type (i.e. it doesn't specify the type of elements stored in the Vector), firstElement() returns an object of type Object, which must be cast to type Customer in order to be assigned to a Customer variable.

Replacing

private java.util.Vector customers = new java.util.Vector();

with

private java.util.Vector<Customer> customers = new java.util.Vector<>();

would allow to simply assign the first element of the Vector without casting :

Customer customer = customers.firstElement();
Eran
  • 387,369
  • 54
  • 702
  • 768