JAVA中的語法糖
啥也不說直接上代碼
情景一:
public class ParameterizedType {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String, String>();
map.put("1", "OK");
map.put("2", "hello");
System.out.println(map.get("1"));
System.out.println(map.get("2"));
}
}
這個沒有問題吧,就是一個map,放兩條數據,再打印下。不急我們先用Java Decompiler 弄下,結果如下:
public class ParameterizedType
{
public static void main(String[] args)
{
Map map = new HashMap();
map.put("1", "OK");
map.put("2", "hello");
System.out.println((String)map.get("1"));
System.out.println((String)map.get("2"));
}
}
問題來了,這就是泛型嗎?這不是真泛型。
情景二:
在一類裏出現如下代碼,編譯能通過嗎
public void test(List<String> list) {
}
public void test(List<Integer> list) {
}
反編譯下:
public void test(List<String> list)
{
throw new Error("Unresolved compilation problem: \n\tMethod test(List<String>) has the same erasure test(List<E>) as another method in type ParameterizedType\n");
}
編譯不通過,報錯了。修改下代碼如下:
public void test(List<String> list) {
}
public int test(List<Integer> list) {
return 1;
}
看看反編譯後的代碼先:
public void test(List<String> list) {
}
public int test(List<Integer> list) {
return 1;
}
編譯通過了,這是怎麼回事呢,看看修改的那部份代碼
修改內容有:將第二個test方法返回類型爲int,並且添加return語句。居然能通過。難道返回值也參與重載?
情景三:
public void test(){
List<Integer> list = Arrays.asList(0,1,2,3,4);
for (Integer integer : list) {
}
}
反編譯下:
List list = Arrays.asList(new Integer[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4) });
int sum = 0;
Integer localInteger;
for (Iterator localIterator = list.iterator(); localIterator.hasNext(); localInteger = (Integer)localIterator.next());
}
情景四:
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a + b));
System.out.println(c.equals(a + b));
System.out.println(g == (a + b));
System.out.println(g.equals(a + b));
}
運行結果如下:
true
false
true
true
true
false
反編譯下:
public static void main(String[] args) {
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(2);
Integer c = Integer.valueOf(3);
Integer d = Integer.valueOf(3);
Integer e = Integer.valueOf(321);
Integer f = Integer.valueOf(321);
Long g = Long.valueOf(3L);
System.out.println(c == d);
System.out.println(e == f);
System.out.println(c.intValue() == a.intValue() + b.intValue());
System.out.println(c.equals(Integer.valueOf(a.intValue() + b.intValue())));
System.out.println(g.longValue() == a.intValue() + b.intValue());
System.out.println(g.equals(Integer.valueOf(a.intValue() + b.intValue())));
}
各種語言或多或少都有語法糖有存在,方便開發,加快開發效率。有些時候,還是想看一下語法糖背後的東西呀~!提醒自己在以後的開發注意語法,減少出錯。