JAVA中的语法糖
啥也不说直接上代码
情景一:
<b>public</b> <b>class</b> ParameterizedType {
<b>public</b> <b>static</b> <b>void</b> main(String[] args) {
Map<String,String> map = <b>new</b> 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"));
}
问题来了,这就是泛型吗?这不是真泛型。
情景二:
在一类里出现如下代码,编译能通过吗
<b>public</b> <b>void</b> test(List<String> list) {
<b>public</b> <b>void</b> 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");
编译不通过,报错了。修改下代码如下:
<b>public</b> <b>int</b> test(List<Integer> list) {
<b>return</b> 1;
看看反编译后的代码先:
public void test(List<String> list) {
public int test(List<Integer> list) {
return 1;
编译通过了,这是怎么回事呢,看看修改的那部份代码
修改内容有:将第二个test方法返回类型为int,并且添加return语句。居然能通过。难道返回值也参与重载?
情景三:
<b>public</b> <b>void</b> test(){
List<Integer> list = Arrays.asList(0,1,2,3,4);
<b>for</b> (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());
情景四:
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
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())));
各种语言或多或少都有语法糖有存在,方便开发,加快开发效率。有些时候,还是想看一下语法糖背后的东西呀~!提醒自己在以后的开发注意语法,减少出错。