android guava
TRANSCRIPT
GuavaTing Cheng
Write less code
Write cleaner code
Write more readable code
• “Null sucks” - Java Collections 群集框架及 JSR166
參與者之一, Doug Lea。
• “I call it my billion-dollar mistake” - 圖靈獎得主、快速排序發明者, Tony Hoare 在 QCon London 2009 主講《Null References: The Billion Dollar Mistake》場次時的一段話。
• 95% of collections weren’t supposed to have null
values. - google。
com.google.guava:guava:15.0
Avoid using nullBASIC
……
private String name = null;
public String getName() {
return name;
}
……
名字是 怒爾?
null point excpetion
Optional<T>
private String name = null;
public Optional<String> getName() {
if (name == null)
return Optional.absent();
else
return Optional.of(name);
}
//return “it empty”
getName().or(“it empty”)
//return false
getName().isPresent();
//return null
getName().orNull();
String name =
Optional.fromNullable(getName()).or(“it empty”)
我有偶像包袱不想改 !
PreconditionsBASIC
……
private String name = null;
……
public void setName(String name) {
this.name = name;
}
if (name == null)
throw new NullPointerException();
if (name.length() > 10)
throw new IllegalArgumentException("Name invalid”);
……
public void setName(String name){
this.name = name;
}
……
Preconditions.checkNotNull(name);
Preconditions.checkArgument(
name.length() < 10,
"Name invalid”
);
Preconditions.checkArgument();
Preconditions.checkPositionIndex();
Preconditions.checkNotNull();
Preconditions.checkElementIndex();
Preconditions.checkState();
ThrowablesBASIC
• unchecked exceptions (runtime)
• checked exceptions
……
try {
API.getInstance().getChannel()
} catch (xxx e) {
xxxx
} catch (xxx e) {
xxxx
} catch (APIException e) {
handle(e)
throw new APIException();
} catch (CookieException e) {
handle(e)
throw new CookieException();
} catch (LoginException e) {
handle(e)
throw new CookieException();
}
……
Java 7
……
try {
API.getInstance().getChannel()
} catch (xxx e) {
xxxx
} catch (xxx e) {
xxxx
} catch (APIException |
CookieException |
LoginException e) {
handle(e)
throw e;
}
……
try {
API.getInstance().getChannel();
} catch (xxxx e) {
xxxx
} catch (Throwable e) {
handle(e);
Throwables.propagateIfPossible(e,
APIException.class
);
Throwables.propagateIfPossible(e,
LoginException.class
);
Throwables.propagateIfPossible(e,
CookieException.class
);
throw Throwables.propagate(t);
}
try { // case 1
xxxxx;
} catch (FileNotFoundException |
IOException e) {
e.printStackTrace();
}
try { //case 2
xxxxx;
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
Functional Idiom
Javascript
var lengthFunction = function(str) {
return str.length;
}
console.log(lengthFunction("hello"));
Java
Function<String, Integer> lengthFunction = new
Function<String, Integer>() {
@Override
public Integer apply(String arg0) {
return arg0.length();
}
};
System.out.println(lengthFunction.apply("hello"));
Collections
List<String> words = Arrays.asList(
“one”, “two",
“three", “one”,
“three”
);
Set<String> wordSet = new HashSet<>(words);
// return [two, one, three]
Map<String, Integer> counts = new HashMap<>();
for(String word : words) {
Integer count = counts.get(word);
counts.put(word, count == null ? 1 : count + 1);
}
不重複
每個重複數
多重集合(Multiset)
List<String> words = Arrays.asList(
"one", "two",
"three", “one",
"three");
330 中正路, 900 中正路100 承德路, 330 承德路
Map<Integer, List<Address>> bag = new HashMap<>();
Multimap
Multiset<String> wordBag =
HashMultiset.create(words);
// return [two, one x 2, three x 2]
Multimap<Integer, Address> bag =
HashMultimap.create();
bag.put(330, 中正路);
bag.put(900, 中正路);
bag.put(100, 承德路);
bag.put(330, 承德路);
Key 和 Value 都可以重複,一般的 Map Key 不能重複會被蓋掉
我要找 Map 裡面的 Value
for(Entry<Key, Value> userEntry: map.entrySet()) {
if(name.equals(userEntry.getValue())) {
return map.getKey();
}
}
(Bi-directional map)
BiMap<Key, Value> userBiMap =
HashBiMap.create(map)
userBiMap.inverse().get(value);
// return value
Key 和 Value 不能重複
Ranges
// 1 ~ 10
List<Integer> list = new ArrayList<>(20);
for(int i = 1; i <= 20; i++) {
list.add(i);
}
// a ~ z
List<Character> list = new ArrayList<>(26);
for(char c = 'a'; c <= 'z'; c++) {
list.add(c);
}
那如果 10 ~ +∞ ???
Range.closed(1, 20)
(a..b) {x | a < x < b} open
[a..b] {x | a <= x <= b} closed
(a..b] {x | a < x <= b} openClosed
[a..b) {x | a <= x < b} closedOpen
(a..+∞) {x | x > a} greaterThan
[a..+∞) {x | x >= a} atLeast
(-∞..b) {x | x < b} lessThan
(-∞..b] {x | x <= b} atMost
(-∞..+∞) {x} all
Range<Integer> range = Range.closed(1, 10);
range.contains(5);
range.contains(11);
System.out.println(range);
ContiguousSet<Integer> list =
ContiguousSet.create(
range,
DiscreteDomain.integers()
);
for (int i: list) {
System.out.println(i);
}
Hashing
怎麼產生 MD5?
<?php
$str = ‘miiicasa’;
echo md5($str);
?>
public static String md5Java(String message) {
String digest = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(message.getBytes("UTF-8"));
String StringBuilder sb = new StringBuilder(2*hash.length);
for(byte b : hash){
sb.append(String.format("%02x", b&0xff));
}
digest = sb.toString();
} catch (UnsupportedEncodingException ex) {
throw Throwables.propagate(ex);
} catch (NoSuchAlgorithmException ex) {
throw Throwables.propagate(ex);
}
return digest;
}
HashFunction hf = Hashing.md5();
hf.hashString("miiicasa", Charsets.UTF_8)
// more hash functions
Hashing.md5();
Hashing.murmur3_32();
Hashing.murmur3_128();
Hashing.sha1();
Hashing.sha256();
Hashing.sha512();
Hash
Bloom Filter
判斷一個元素有沒有在集合裡面?
資料量越來越大 O(n), O(longN)
Q & A
Demo