The fun program of the topic 1:sets
public class ShortSet{
public static void main(String args[]) {
Set<Short> s = new HashSet<Short>();
for (short i=0; i<100; i++) {
s.add(i);
s.remove(i-1);
}
System.out.println(s.size());
}
}
Options
(a) 1
(b) 100
(c) Throws exception
(d) None of the above
Answer (b) 100
Analysis process
1 adds a short value to the set, but deletes the integer value. (Translator: From the message, it's nice to see some friends see this)
2 The line program, S.remove (I-1), in which the i-1 is an indication of the return value of int. If I is a short or byte type, it must return an int or a long value when it is arithmetic with int or long.
3 when the S.remove method is executed, the int value above will be autobox into an integer object.
4 Note that a short object containing a value of 1 and an integer object containing a value of 1 are not considered equivalent in comparison.
5 after adding the short object in set, the integer object is deleted, and the latter command is not run (no-op). The compiler also does not complain.
Lessons learned
1 in Java1.5, the set interface is defined in this way:
public interface Set<E>extends Collection<E> {
public abstract boolean add(E e);
public abstract boolean remove(Object o);
...
}
According to the above definition, the parameter types passed in in the Add method must be consistent with the type defined in the set, otherwise the compiler will complain. However, the Remove method does not have this restriction, it accepts the type is object, so you can remove any type, which is called type safe. This is done during the generifying of the collection in 1.5, in order to retain support for the methods in previous versions.
2 The following changes can be made to the program to solve the problem: (short) (i-1); The (i-1) int is then cast to short, and then it is autobox into a short object, so that the short of the preceding line in set is deleted and the final answer becomes (a). So, any operation that involves between different numeric types (byte, short, char, and Int,long), the value returned must be int or long. Be careful and try not to mix. Use int or long as much as possible.