Java 解惑知多少三
17. 不要使用基于减法的比较器
Comparator<Integer> c = new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return i1 - i2;// 升序 } }; List<Integer> l = new ArrayList<Integer>(); l.add(new Integer(-2000000000)); l.add(new Integer(2000000000)); Collections.sort(l, c); System.out.println(l);// [2000000000, -2000000000] int x = -2000000000; int y = 2000000000; /* * -2000000000 即 -(01110111001101011001010000000000) * 的补码为: 10001000110010100110110000000000 * * 计算过程使用竖式表示: * 10001000110010100110110000000000 * 10001000110010100110110000000000 * -------------------------------- * 00010001100101001101100000000000 * * 计算结果溢出,结果为294967296 */ System.out.println(x - y);// 294967296
public int compare(Integer i1, Integer i2) { return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1)); } int i=-(2147483648);
long i=–(9223372036854775808L);
//\u0022是双引号的Unicode编码表示 System.out.println("a\u0022.length() + \u0022b".length());// 2 String line = (String)System.getProperties().get("line.separator"); for(int i =0; i < line.length();i++){ System.out.println((int)line.charAt(i)); } byte bts[] = new byte[256]; for (int i = 0; i < 256; i++) { bts[i] = (byte) i; } // String str = new String(bts,"ISO8859-1");//正确的做法 String str = new String(bts);//使用操作系统默认编码方式编码(XP GBK) for (int i = 0, n = str.length(); i < n; i++) { System.out.print((int) str.charAt(i) + " "); } System.getProperty("file.encoding");//jdk1.4或之前版本 java.nio.charset.Charset.defaultCharset();//jdk1.5或之后版本 System.out.println(".".replaceAll(".class", "\\$")); System.out.println(".class".replaceAll("\\.", "\\\\\\$")); System.out.println(".class".replaceAll("\\Q.\\E", "\\\\\\$")); System.out.println(".class".replaceAll(Pattern.quote("."), Matcher.quoteReplacement("\\$"))); System.out.println(".".replace('.','\\'));//能将 . 替换成 \ System.out.println(".".replace('.','$')); //能将 . 替换成 $ Random rnd = new Random(); StringBuffer word = null; switch (rnd.nextInt(3)) { case 1: word = new StringBuffer("P"); break; case 2: word = new StringBuffer("G"); break; default: word = new StringBuffer("M"); break;// 可以不要 } word.append('a'); word.append('i'); word.append('n'); System.out.println(word);