原文地址:http://macrochen.iteye.com/blog/1393502
http://www.odi.ch/prog/design/newbies.php
每天在写Java程序, 其实里面有一些细节大家可能没怎么注意, 这不, 有人总结了一个我们编程中常见的问题. 虽然一般没有什么大问题, 但是最好别这样做. 另外这里提到的很多问题其实可以通过Findbugs(http://findbugs.sourceforge.net/ )来帮我们进行检查出来.
字符串连接误用
错误的写法:
正确的写法:
StringBuilder sb = new StringBuilder(persons.size() * 16); // well estimated buffer for (Person p : persons) { if (sb.length() > 0) sb.append(", "); sb.append(p.getName); }
StringBuffer sb = new StringBuffer(); sb.append("Name: "); sb.append(name + '\n'); sb.append("!"); ... String s = sb.toString();
StringBuilder sb = new StringBuilder(100); sb.append("Name: "); sb.append(name); sb.append("\n!"); String s = sb.toString();
String s = "Name: " + name + "\n!";
if (name.compareTo("John") == 0) ... if (name == "John") ... if (name.equals("John")) ... if ("".equals(name)) ...
if ("John".equals(name)) ... if (name.length() == 0) ... if (name.isEmpty()) ...
"" + set.size() new Integer(set.size()).toString()
String.valueOf(set.size())
zero = new Integer(0); return Boolean.valueOf("true");
zero = Integer.valueOf(0); return Boolean.TRUE;
int start = xml.indexOf("<name>") + "<name>".length(); int end = xml.indexOf("</name>"); String name = xml.substring(start, end);
SAXBuilder builder = new SAXBuilder(false); Document doc = doc = builder.build(new StringReader(xml)); String name = doc.getRootElement().getChild("name").getText();
String name = ... String attribute = ... String xml = "<root>" +"<name att=\""+ attribute +"\">"+ name +"</name>" +"</root>";
Element root = new Element("root"); root.setAttribute("att", attribute); root.setText(name); Document doc = new Documet(); doc.setRootElement(root); XmlOutputter out = new XmlOutputter(Format.getPrettyFormat()); String xml = out.outputString(root);
String xml = FileUtils.readTextFile("my.xml");
Reader r = new FileReader(file); Writer w = new FileWriter(file); Reader r = new InputStreamReader(inputStream); Writer w = new OutputStreamWriter(outputStream); String s = new String(byteArray); // byteArray is a byte[] byte[] a = string.getBytes();
Reader r = new InputStreamReader(new FileInputStream(file), "ISO-8859-1"); Writer w = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1"); Reader r = new InputStreamReader(inputStream, "UTF-8"); Writer w = new OutputStreamWriter(outputStream, "UTF-8"); String s = new String(byteArray, "ASCII"); byte[] a = string.getBytes("ASCII");
InputStream in = new FileInputStream(file); int b; while ((b = in.read()) != -1) { ... }
InputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] pdf = toPdf(file);
File pdf = toPdf(file);
Socket socket = ... socket.connect(remote); InputStream in = socket.getInputStream(); int i = in.read();
Socket socket = ... socket.connect(remote, 20000); // fail after 20s InputStream in = socket.getInputStream(); socket.setSoTimeout(15000); int i = in.read();
for (...) { long t = System.currentTimeMillis(); long t = System.nanoTime(); Date d = new Date(); Calendar c = new GregorianCalendar(); }
Date d = new Date(); for (E entity : entities) { entity.doSomething(); entity.setUpdated((Date) d.clone()); }
private volatile long time; Timer timer = new Timer(true); try { time = System.currentTimeMillis(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { time = System.currentTimeMillis(); } }, 0L, 10L); // granularity 10ms for (E entity : entities) { entity.doSomething(); entity.setUpdated(new Date(time)); } } finally { timer.cancel(); }
Query q = ... Person p; try { p = (Person) q.getSingleResult(); } catch(Exception e) { p = null; }
Query q = ... Person p; try { p = (Person) q.getSingleResult(); } catch(NoResultException e) { p = null; }
try { doStuff(); } catch(Exception e) { log.fatal("Could not do stuff"); } doMoreStuff();
try { doStuff(); } catch(Exception e) { throw new MyRuntimeException("Could not do stuff because: "+ e.getMessage, e); }
try { doStuff(); } catch(Exception e) { throw new RuntimeException(e); }
try { doStuff(); } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new RuntimeException(e.getMessage(), e); } try { doStuff(); } catch(IOException e) { throw new RuntimeException(e.getMessage(), e); } catch(NamingException e) { throw new RuntimeException(e.getMessage(), e); }
try { } catch(ParseException e) { throw new RuntimeException(); throw new RuntimeException(e.toString()); throw new RuntimeException(e.getMessage()); throw new RuntimeException(e); }
try { } catch(ParseException e) { throw new RuntimeException(e.getMessage(), e); }
try { ... } catch(ExceptionA e) { log.error(e.getMessage(), e); throw e; } catch(ExceptionB e) { log.error(e.getMessage(), e); throw e; }
try { is = new FileInputStream(inFile); os = new FileOutputStream(outFile); } finally { try { is.close(); os.close(); } catch(IOException e) { /* we can't do anything */ } }
try { is = new FileInputStream(inFile); os = new FileOutputStream(outFile); } finally { try { if (is != null) is.close(); } catch(IOException e) {/* we can't do anything */} try { if (os != null) os.close(); } catch(IOException e) {/* we can't do anything */} }
try { ... do risky stuff ... } catch(SomeException e) { // never happens } ... do some more ...
try { ... do risky stuff ... } catch(SomeException e) { // never happens hopefully throw new IllegalStateException(e.getMessage(), e); // crash early, passing all information } ... do some more ...
public class A implements Serializable { private String someState; private transient Log log = LogFactory.getLog(getClass()); public void f() { log.debug("enter f"); ... } }
public class A implements Serializable { private String someState; private static final Log log = LogFactory.getLog(A.class); public void f() { log.debug("enter f"); ... } } public class A implements Serializable { private String someState; public void f() { Log log = LogFactory.getLog(getClass()); log.debug("enter f"); ... } }
public class B { private int count = 0; private String name = null; private boolean important = false; }
public class B { private int count; private String name; private boolean important; }
private static final Log log = LogFactory.getLog(MyClass.class);
Class clazz = Class.forName(name); Class clazz = getClass().getClassLoader().loadClass(name);
ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) cl = MyClass.class.getClassLoader(); // fallback Class clazz = cl.loadClass(name);
Class beanClass = ... if (beanClass.newInstance() instanceof TestBean) ...
Class beanClass = ... if (TestBean.class.isAssignableFrom(beanClass)) ...
Collection l = new Vector(); for (...) { l.add(object); }
Collection l = new ArrayList(); for (...) { l.add(object); }
ArrayList | LinkedList | |
add (append) | O(1) or ~O(log(n)) if growing | O(1) |
insert (middle) | O(n) or ~O(n*log(n)) if growing | O(n) |
remove (middle) | O(n) (always performs complete copy) | O(n) |
iterate | O(n) | O(n) |
get by index | O(1) | O(n) |
Map map = new HashMap(collection.size()); for (Object o : collection) { map.put(o.key, o.value); }
Map map = new HashMap(1 + (int) (collection.size() / 0.75));
List<Integer> codes = new ArrayList<Integer>(); codes.add(Integer.valueOf(10)); codes.add(Integer.valueOf(20)); codes.add(Integer.valueOf(30)); codes.add(Integer.valueOf(40));
int[] codes = { 10, 20, 30, 40 };
// horribly slow and a memory waster if l has a few thousand elements (try it yourself!) List<Mergeable> l = ...; for (int i=0; i < l.size()-1; i++) { Mergeable one = l.get(i); Iterator<Mergeable> j = l.iterator(i+1); // memory allocation! while (j.hasNext()) { Mergeable other = l.next(); if (one.canMergeWith(other)) { one.merge(other); other.remove(); } } }
// quite fast and no memory allocation Mergeable[] l = ...; for (int i=0; i < l.length-1; i++) { Mergeable one = l[i]; for (int j=i+1; j < l.length; j++) { Mergeable other = l[j]; if (one.canMergeWith(other)) { one.merge(other); l[j] = null; } } }
/** * @returns [1]: Location, [2]: Customer, [3]: Incident */ Object[] getDetails(int id) {...
Details getDetails(int id) {...} private class Details { public Location location; public Customer customer; public Incident incident; }
public void notify(Person p) { ... sendMail(p.getName(), p.getFirstName(), p.getEmail()); ... } class PhoneBook { String lookup(String employeeId) { Employee emp = ... return emp.getPhone(); } }
public void notify(Person p) { ... sendMail(p); ... } class EmployeeDirectory { Employee lookup(String employeeId) { Employee emp = ... return emp; } }
private String name; public void setName(String name) { this.name = name.trim(); } public void String getName() { return this.name; }
person.setName(textInput.getText().trim());
Calendar cal = new GregorianCalender(TimeZone.getTimeZone("Europe/Zurich")); cal.setTime(date); cal.add(Calendar.HOUR_OF_DAY, 8); date = cal.getTime();
date = new Date(date.getTime() + 8L * 3600L * 1000L); // add 8 hrs
Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date startOfDay = cal.getTime();
Calendar cal = new GregorianCalendar(user.getTimeZone()); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date startOfDay = cal.getTime();
public static Date convertTz(Date date, TimeZone tz) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTime(date); cal.setTimeZone(tz); return cal.getTime(); }
Calendar c = Calendar.getInstance(); c.set(2009, Calendar.JANUARY, 15);
Calendar c = new GregorianCalendar(timeZone); c.set(2009, Calendar.JANUARY, 15);
account.changePassword(oldPass, newPass); Date lastmod = account.getLastModified(); lastmod.setTime(System.currentTimeMillis());
account.changePassword(oldPass, newPass); account.setLastModified(new Date());
public class Constants { public static final SimpleDateFormat date = new SimpleDateFormat("dd.MM.yyyy"); }
public interface Constants { String version = "1.0"; String dateFormat = "dd.MM.yyyy"; String configFile = ".apprc"; int maxNameLength = 32; String someQuery = "SELECT * FROM ..."; }
public int getFileSize(File f) { long l = f.length(); return (int) l; }
public int getFileSize(File f) { long l = f.length(); if (l > Integer.MAX_VALUE) throw new IllegalStateException("int overflow"); return (int) l; }
long a = System.currentTimeMillis(); long b = a + 100; System.out.println((int) b-a); System.out.println((int) (b-a));
for (float f = 10f; f!=0; f-=0.1) { System.out.println(f); }
for (float f = 10f; f>0; f-=0.1) { System.out.println(f); }
float total = 0.0f; for (OrderLine line : lines) { total += line.price * line.count; } double a = 1.14 * 75; // 85.5 将表示为 85.4999... System.out.println(Math.round(a)); // 输出值为85 BigDecimal d = new BigDecimal(1.14); //造成精度丢失
BigDecimal total = BigDecimal.ZERO; for (OrderLine line : lines) { BigDecimal price = new BigDecimal(line.price); BigDecimal count = new BigDecimal(line.count); total = total.add(price.multiply(count)); // BigDecimal is immutable! } total = total.setScale(2, RoundingMode.HALF_UP); BigDecimal a = (new BigDecimal("1.14")).multiply(new BigDecimal(75)); // 85.5 exact a = a.setScale(0, RoundingMode.HALF_UP); // 86 System.out.println(a); // correct output: 86 BigDecimal a = new BigDecimal("1.14");
public void save(File f) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(f)); out.write(...); out.close(); } public void load(File f) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(f)); in.read(...); in.close(); }
// code for your cookbook public void save() throws IOException { File f = ... OutputStream out = new BufferedOutputStream(new FileOutputStream(f)); try { out.write(...); out.flush(); // don't lose exception by implicit flush on close } finally { out.close(); } } public void load(File f) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(f)); try { in.read(...); } finally { try { in.close(); } catch (IOException e) { } } }
Car getCar(DataSource ds, String plate) throws SQLException { Car car = null; Connection c = null; PreparedStatement s = null; ResultSet rs = null; try { c = ds.getConnection(); s = c.prepareStatement("select make, color from cars where plate=?"); s.setString(1, plate); rs = s.executeQuery(); if (rs.next()) { car = new Car(); car.make = rs.getString(1); car.color = rs.getString(2); } } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (s != null) try { s.close(); } catch (SQLException e) { } if (c != null) try { c.close(); } catch (SQLException e) { } } return car; }
public class FileBackedCache { private File backingStore; ... protected void finalize() throws IOException { if (backingStore != null) { backingStore.close(); backingStore = null; } } }
public class FileBackedCache { private File backingStore; ... public void close() throws IOException { if (backingStore != null) { backingStore.close(); backingStore = null; } } }
try (Writer w = new FileWriter(f)) { // implements Closable w.write("abc"); // w goes out of scope here: w.close() is called automatically in ANY case } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); }
try { Thread.sleep(1000); } catch (InterruptedException e) { // ok } or while (true) { if (Thread.interrupted()) break; }
try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } or while (true) { if (Thread.currentThread().isInterrupted()) break; }
class Cache { private static final Timer evictor = new Timer(); }
class Cache { private static Timer evictor; public static setupEvictor() { evictor = new Timer(); } }
final MyClass callback = this; TimerTask task = new TimerTask() { public void run() { callback.timeout(); } }; timer.schedule(task, 300000L); try { doSomething(); } finally { task.cancel(); }
TimerTask task = new Job(this); timer.schedule(task, 300000L); try { doSomething(); } finally { task.cancel(); } static class Job extends TimerTask { private MyClass callback; public Job(MyClass callback) { this.callback = callback; } public boolean cancel() { callback = null; return super.cancel(); } public void run() { if (callback == null) return; callback.timeout(); } }