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"));
}
}
程序输出为false false
Boolean.getBoolean(s);当且仅当以参数命名的系统属性存在,且等于 "true"
字符串时,才返回 true
。
2:
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public class InstrumentedHashSet<E> extends HashSet<E> {
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);
}
}
结果为:6
因为在HashSet里,addall方法是用add实现的,相当于两次调用add方法。在effective Java里面有详细的介绍
3:
import java.util.Iterator;
import java.util.NoSuchElementException;
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());
}
}
}
4:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
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,在compare方法中==在比较对象的时候出问题...
5:
public class ThreadFriendly {
ThreadLocal<Value> threadLocalPart = new ThreadLocal<Value>();
class Value{
final int i;
Value(int i){
this.i = i;
}
}
ThreadFriendly setThreadVal(int i){
threadLocalPart.set(new Value(i));
return this;
}
int getThreadVal(){
return threadLocalPart.get().i;
}
public static void main(String[] args) {
int sum = 0;
for(int i = -500000;i<=500000;i++){
sum+= new ThreadFriendly().setThreadVal(i).getThreadVal();
}
System.out.println(sum);
}
}
非静态内部类都持有一个外部对象 的引用,这样导致内存溢出