新規vs valueOf
//
Integer i = new Integer(100);
Long l = new Long(100);
String s = new String("A");
//
Integer i = Integer.valueOf(100);
Long l = 100L;// Long.valueOf(100L);
String s = "A";
valueOf , , . , , , Byte Long . -128 127. , , . 3.5 + . , . , , Integer «java.lang.Integer.IntegerCache.high», -XX:AutoBoxCacheMax=<size>.
+ vs append
//
String[] fields = new String[] {"a","b","c","d","e","f","g"};
String s = "";
for (int i = 0; i < fields.length; i++) {
s = s + fields[i];
}
return s;
//
String[] fields = new String[] {"a","b","c","d","e","f","g"};
StringBuilder s = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
s.append(fields[i]);
}
return s.toString();
( +) , , . , «s = s + fileds[i]» 3 : StringBuilder s, append, toString ( : s = new StringBuilder(s).append(fields[i]).toString();). 3 ! s + fileds[i] , .
StringBuilder vs StringBuffer
StringBuilder, , StringBuffer, StringBuilder StringBuffer , .
instanceOf
instanceOf. java . — , . .
P. S. « java ». . , , , , , instanceOf , , '*'.
Generics
//
List a = new ArrayList();
//
List<String> a = new ArrayList<String>();
, . 2- : . . - . — <?>, <? extends someType> / instanceOf.
Interface for Consts
//
interface A {
public static final String A = "a";
}
//
final class A {
public static final String A = "a";
}
. . , . , , java .
Override
Override , . ( , ).
null vs empty
null , null- . Collections :
Collections.emptyList(); Collections.emptyMap(); Collections.emptySet();
. :
Set<Document> docs = getDocuments(plan);
for (Document doc : docs) {
sendMessage(doc.getOwner());
}
public static Set<Document> getDocuments(Plan plan) {
//some logic
if (isDoSomethingOk() && hasAccessToDocuments(user)) {
return plan.getDocuments();
}
return Collections.emptySet();
}
, . , , null . — « » , .
//
int a = 12;
String s = a + "";
//
int a = 12;
String s = String.valueOf(a);
.
, , , , , .