程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> java7新特性之Diamond syntax

java7新特性之Diamond syntax

編輯:JAVA綜合教程

java7新特性之Diamond syntax


java7新特性之Diamond syntax

Java 7 also introduces a change that means less typing for you when dealing with
generics. One of the problems with generics is that the definitions and setup of
instances can be really verbose. Let’s suppose that you have some users, whom you
identify by userid (which is an integer), and each user has one or more lookup tables
specific to that user. What would that look like in code?
 

Map<integer, string="">> usersLists =
new HashMap<integer, string="">>();</integer,></integer,>

That’s quite a mouthful, and almost half of it is duplicated characters. Wouldn’t it be
better if you could write something like this,
Map> usersLists = new HashMap<>();

and have the compiler work out the type information on the right side? Thanks to the
magic of Project Coin, you can. In Java 7, the shortened form for declarations like that
is entirely legal. It’s backwards compatible as well, so when you find yourself revisiting
old code, you can cut the older, more verbose declaration and start using the new
type-inferred syntax to save a few pixels.
We should point out that the compiler is using a new form of type inference for
this feature. It’s working out the correct type for the expression on the right side, and
isn’t just substituting in the text that defines the full type.

 

The “diamond syntax” name
This form is called “diamond syntax” because, well, the shortened type information
looks like a diamond. The proper name in the proposal is “Improved Type Inference
for Generic Instance Creation,” which is a real mouthful and has ITIGIC as an acronym, which sounds stupid, so diamond syntax it is.
 

讀書筆記:The Well-Grounded Java Develope

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved