http://zangxt.iteye.com/blog/435711
1
public class SimpleQuestion {
static boolean yesOrNo(String s) {
s = s.toLowerCase();
if (s.equals("yes") || s.equals("y") || s.equals("t")) {
s = "true";
}
return Boolean.getBoolean(s);
}
public static void main(String[] args) {
System.out.println(yesOrNo("true") + " " + yesOrNo("Yes"));
}
}
输出是什么?
转载者评论:这个纯粹是用过就知道,不用过很难猜到
2
package test;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public class InstrumentedHashSet<E> extends HashSet<E> {
/**
*
*/
private static final long serialVersionUID = 1L;
private int addCount = 0;
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public static void main(String[] args) {
InstrumentedHashSet<String> s = new InstrumentedHashSet<String>();
s.addAll(Arrays.asList("Accordion", "Banjo", "Kazoo"));
System.out.println(s.addCount);
}
}
输出是什么?
转载者评论:理解了覆盖方法后剩下的就是要细心了,相较而言,这题比上面那道题简单,毕竟考的都是常见的东西。
3
public abstract class AbstractIterator<T> implements Iterator<T> {
T next = nextElement();
public boolean hasNext() {
return next != null;
}
public T next() {
if (next == null) {
throw new NoSuchElementException();
}
T result = next;
next = nextElement();
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
protected abstract T nextElement();
private static Iterator<Character> test(final String s) {
return new AbstractIterator<Character>() {
private int cursor = 0;
protected Character nextElement() {
return cursor == s.length() ? null : s.charAt(cursor++);
}
};
}
public static void main(String[] args) {
for (Iterator<Character> i = test("OPS"); i.hasNext();) {
System.out.print(i.next());
}
}
}
输出的结果是什么?
转载者评论:开始想当然以为输出的就是ops,知道错了一想,应该是初始化的顺序问题,最开始初始化的时候先执行了T next = nextElement()这个方法,到之后了next=o,cursor=1,但是随后到了cursor =0这步,功亏一篑,cursor归零了。后来循环时,就多输出了一个o。
4
public class Searching {
public static void main(String[] args) {
String[] strings = { "0", "1", "2", "3", "4", "5" };
List<Integer> integers = new ArrayList<Integer>();
for (String s : strings) {
integers.add(Integer.valueOf(s));
}
System.out.println(Collections.binarySearch(integers, 1, cmp));
}
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
};
}
打印结果是什么?
转载者评论:这个想了很久,按理来说正确输出应该是2,但是实际输出时-2。后来才知道是i==j这里有问题,做了一些测试,integer不要用==来做比较,特别是建立新对象的时候。