-2

I'm new to java, I have the code below (v is a vector) and I don't understand this:

(Customer) v.get(i)

Please explain to me .tks

public void insert(Customer c) {
    boolean checkExist = true;
    if (checkExist && !isIn(c,v)) {
        for (int i = 0; i < v.size(); i++) {
            int check = c.compareTo((Customer) v.get(i));
            if (check < 0) {
                Customer x = new Customer();
                x = (Customer) v.get(i);
                v.set(i, c);
                c = x;
            }
        }
        v.add(c);
    }
}
public boolean isIn(Customer c, Vector els) {
    c = new Customer();
    for (int i = 0; i < els.size(); i++) {
        if (c.equals(els.get(i))) {
            return true;
        }
    }
    return false;
}
Morne
  • 1,623
  • 2
  • 18
  • 33
Smilee
  • 23
  • 4

4 Answers4

0

v.get(i) gets the ith member of v, and (Customer) casts it to a Customer class.

See the tutorial, "Casting Objects."

markspace
  • 10,621
  • 3
  • 25
  • 39
0

It is casting the object returned by v.get(i) to a Customer, so the object returned can be treated as a Customer, accessing methods in the Customer class/interface. If the object returned cannot be cast to a Customer, because it does not extend/implement Customer, it will throw a ClassCastException.

DBug
  • 2,502
  • 1
  • 12
  • 25
0

You don't show us how v is declared.

In the following two lines there's a harmless bug:

Customer x = new Customer();
x = (Customer) v.get(i);

On the first line a new Customer object is created, but it's never being used, and after the assignment on the following line - this object is eligible to garbage-collection.

These two lines can be substituted by:

Customer x = (Customer) v.get(i);

The reason there is a need to use casting (Customer) is in case v is declared to hold a more general type object, and we need to cast it to Customer in order to assign it to x and use Customer properties and methods.

For more about casting see Casting Objects section.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0
x = (Customer) v.get(i);

Means that your typecasting the i-element from your vector to the class Customer. In simpler words making v.get(i) of the type Customer.

Møssi
  • 18
  • 2