Review Questions

graphics/rq_icon.gif

11.14

Given that the objects denoted by the parameters override the equals() and the hashCode() methods appropriately, which return values are possible from the following method?

String func(Object x, Object y) {
    return (x == y) + " " + x.equals(y) + " " + (x.hashCode() == y.hashCode());
}

Select the two correct answers.

  1. "false false true"

  2. "false true false"

  3. "false true true"

  4. "true false false"

  5. "true false true"

11.15

Insert code into the equalsImpl() method in order to provide a correct implementation of the equals() method.

public class Pair {
    int a, b;
    public Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public boolean equals(Object o) {
        return (this == o) || (o instanceof Pair) && equalsImpl((Pair) o);
    }

    private boolean equalsImpl(Pair o) {
        // ... PROVIDE IMPLEMENTATION HERE ...
    }
}

Select the three correct answers.

  1. return a == o.a || b == o.b;

  2. return false;

  3. return a >= o.a;

  4. return a == o.a;

  5. return a == o.a && b == o.b;

11.16

Which collection implementation is thread-safe?

Select the one correct answer.

  1. ArrayList

  2. HashSet

  3. Vector

  4. TreeSet

  5. LinkedList

11.17

Which code provides a correct implementation of the hashCode() method in the following program?

import java.util.*;
public class Measurement {
    int count;
    int accumulated;
    public Measurement() {}
    public void record(int v) {
        count++;
        accumulated += v;
    }
    public int average() {
        return accumulated/count;
    }
    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof Measurement))
            return false;
        Measurement o = (Measurement) other;
        if (count != 0 && o.count != 0)
            return average() == o.average();
        return count == o.count;
    }
    public int hashCode() {
        // ... PROVIDE IMPLEMENTATION HERE ...
    }
}

Select the two correct answers.

  1. return 31337;

  2. return accumulated / count;

  3. return (count << 16) ^ accumulated;

  4. return ~accumulated;

  5. return count == 0 ? 0 : average();



     
    ASPTreeView.com
     
    Evaluation has СЧµУјЅµЧЪЅexpired.
    Info...