摘要:語言特性系列的新特性的新特性的新特性的新特性的新特性的新特性的新特性的新特性的新特性序這是語言特性系列的第一篇,從的新特性開始講起。線程數(shù)達(dá)到后,新增的任務(wù)就放到工作隊列里,而線程池里的線程則努力的使用從工作隊列里拉活來干。
Java語言特性系列
Java5的新特性
Java6的新特性
Java7的新特性
Java8的新特性
Java9的新特性
Java10的新特性
Java11的新特性
Java12的新特性
Java13的新特性
序這是Java語言特性系列的第一篇,從java5的新特性開始講起。初衷就是可以方便的查看語言的演進(jìn)歷史。
特性列表泛型
枚舉
裝箱拆箱
變長參數(shù)
注解
foreach循環(huán)
靜態(tài)導(dǎo)入
格式化
線程框架/數(shù)據(jù)結(jié)構(gòu)
Arrays工具類/StringBuilder/instrument
1、泛型所謂類型擦除指的就是Java源碼中的范型信息只允許停留在編譯前期,而編譯后的字節(jié)碼文件中將不再保留任何的范型信息。也就是說,范型信息在編譯時將會被全部刪除,其中范型類型的類型參數(shù)則會被替換為Object類型,并在實際使用時強制轉(zhuǎn)換為指定的目標(biāo)數(shù)據(jù)類型。而C++中的模板則會在編譯時將模板類型中的類型參數(shù)根據(jù)所傳遞的指定數(shù)據(jù)類型生成相對應(yīng)的目標(biāo)代碼。
Mapsquares = new HashMap ();
通配符類型:避免unchecked警告,問號表示任何類型都可以接受
public void printList(List> list, PrintStream out) throws IOException { for (Iterator> i = list.iterator(); i.hasNext(); ) { out.println(i.next().toString()); } }
限制類型
public static double sum(Box box1,Box box2){ double total = 0; for (Iterator i = box1.contents.iterator(); i.hasNext(); ) { total = total + i.next().doubleValue(); } for (Iterator i = box2.contents.iterator(); i.hasNext(); ) { total = total + i.next().doubleValue(); } return total; }2、枚舉
EnumMap
public void testEnumMap(PrintStream out) throws IOException { // Create a map with the key and a String message EnumMapantMessages = new EnumMap (AntStatus.class); // Initialize the map antMessages.put(AntStatus.INITIALIZING, "Initializing Ant..."); antMessages.put(AntStatus.COMPILING, "Compiling Java classes..."); antMessages.put(AntStatus.COPYING, "Copying files..."); antMessages.put(AntStatus.JARRING, "JARring up files..."); antMessages.put(AntStatus.ZIPPING, "ZIPping up files..."); antMessages.put(AntStatus.DONE, "Build complete."); antMessages.put(AntStatus.ERROR, "Error occurred."); // Iterate and print messages for (AntStatus status : AntStatus.values() ) { out.println("For status " + status + ", message is: " + antMessages.get(status)); } }
switch枚舉
public String getDescription() { switch(this) { case ROSEWOOD: return "Rosewood back and sides"; case MAHOGANY: return "Mahogany back and sides"; case ZIRICOTE: return "Ziricote back and sides"; case SPRUCE: return "Sitka Spruce top"; case CEDAR: return "Wester Red Cedar top"; case AB_ROSETTE: return "Abalone rosette"; case AB_TOP_BORDER: return "Abalone top border"; case IL_DIAMONDS: return "Diamonds and squares fretboard inlay"; case IL_DOTS: return "Small dots fretboard inlay"; default: return "Unknown feature"; } }3、Autoboxing與Unboxing
將primitive類型轉(zhuǎn)換成對應(yīng)的wrapper類型:Boolean、Byte、Short、Character、Integer、Long、Float、Double
public static void m1(Integer i){ System.out.println("this is integer"); } public static void m1(double d){ System.out.println("this is double"); }
m1(1)輸出的是double,方法匹配時線下兼容,不考慮boxing與unboxing。
4、varargprivate String print(Object... values) { StringBuilder sb = new StringBuilder(); for (Object o : values) { sb.append(o.toString()) .append(" "); } return sb.toString(); }5、annotation
Inherited表示該注解是否對類的子類繼承的方法等起作用
@Documented @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface InProgress { }
指定Target
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE}) public @interface TODO { String value(); }
Target類型
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE }
rentation表示annotation是否保留在編譯過的class文件中還是在運行時可讀。
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
通過反射獲取元信息
public class ReflectionTester { public ReflectionTester() { } public void testAnnotationPresent(PrintStream out) throws IOException { Class c = Super.class; boolean inProgress = c.isAnnotationPresent(InProgress.class); if (inProgress) { out.println("Super is In Progress"); } else { out.println("Super is not In Progress"); } } public void testInheritedAnnotation(PrintStream out) throws IOException { Class c = Sub.class; boolean inProgress = c.isAnnotationPresent(InProgress.class); if (inProgress) { out.println("Sub is In Progress"); } else { out.println("Sub is not In Progress"); } } public void testGetAnnotation(PrintStream out) throws IOException, NoSuchMethodException { Class c = AnnotationTester.class; AnnotatedElement element = c.getMethod("calculateInterest", float.class, float.class); GroupTODO groupTodo = element.getAnnotation(GroupTODO.class); String assignedTo = groupTodo.assignedTo(); out.println("TODO Item on Annotation Tester is assigned to: "" + assignedTo + """); } public void printAnnotations(AnnotatedElement e, PrintStream out) throws IOException { out.printf("Printing annotations for "%s"%n%n", e.toString()); Annotation[] annotations = e.getAnnotations(); for (Annotation a : annotations) { out.printf(" * Annotation "%s" found%n", a.annotationType().getName()); } } public static void main(String[] args) { try { ReflectionTester tester = new ReflectionTester(); tester.testAnnotationPresent(System.out); tester.testInheritedAnnotation(System.out); tester.testGetAnnotation(System.out); Class c = AnnotationTester.class; AnnotatedElement element = c.getMethod("calculateInterest", float.class, float.class); tester.printAnnotations(element, System.out); } catch (Exception e) { e.printStackTrace(); } } }6、for/in
for/in循環(huán)辦不到的事情:
(1)遍歷同時獲取index
(2)集合逗號拼接時去掉最后一個
(3)遍歷的同時刪除元素
import static java.lang.System.err; import static java.lang.System.out; import java.io.IOException; import java.io.PrintStream; public class StaticImporter { public static void writeError(PrintStream err, String msg) throws IOException { // Note that err in the parameter list overshadows the imported err err.println(msg); } public static void main(String[] args) { if (args.length < 2) { err.println( "Incorrect usage: java com.oreilly.tiger.ch08 [arg1] [arg2]"); return; } out.println("Good morning, " + args[0]); out.println("Have a " + args[1] + " day!"); try { writeError(System.out, "Error occurred."); } catch (IOException e) { e.printStackTrace(); } } }8、格式化
/** * java.text.DateFormat * java.text.SimpleDateFormat * java.text.MessageFormat * java.text.NumberFormat * java.text.ChoiceFormat * java.text.DecimalFormat */ public class FormatTester { public static void printf() { //printf String filename = "this is a file"; try { File file = new File(filename); FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String line; int i = 1; while ((line = reader.readLine()) != null) { System.out.printf("Line %d: %s%n", i++, line); } } catch (Exception e) { System.err.printf("Unable to open file named "%s": %s", filename, e.getMessage()); } } public static void stringFormat() { // Format a string containing a date. Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke"s Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke"s Birthday: May 23, 1995" System.out.println(s); } public static void formatter() { StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d"); // -> " d c b a" // Optional locale as the first argument can be used to get // locale-specific formatting of numbers. The precision and width can be // given to round and align the value. formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); // -> "e = +2,7183" // The "(" numeric flag may be used to format negative numbers with // parentheses rather than a minus sign. Group separators are // automatically inserted. formatter.format("Amount gained or lost since last statement: $ %(,.2f", 6217.58); // -> "Amount gained or lost since last statement: $ (6,217.58)" } public static void messageFormat() { String msg = "歡迎光臨,當(dāng)前({0})等待的業(yè)務(wù)受理的顧客有{1}位,請排號辦理業(yè)務(wù)!"; MessageFormat mf = new MessageFormat(msg); String fmsg = mf.format(new Object[]{new Date(), 35}); System.out.println(fmsg); } public static void dateFormat(){ String str = "2010-1-10 17:39:21"; SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); try { System.out.println(format.format(format.parse(str))); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { formatter(); stringFormat(); messageFormat(); dateFormat(); printf(); } }9、threading
uncaught exception
public class BubbleSortThread extends Thread { private int[] numbers; public BubbleSortThread(int[] numbers) { setName("Simple Thread"); setUncaughtExceptionHandler( new SimpleThreadExceptionHandler()); this.numbers = numbers; } public void run() { int index = numbers.length; boolean finished = false; while (!finished) { index--; finished = true; for (int i=0; inumbers[i+1]) { // swap int temp = numbers[i]; numbers[i] = numbers[i+1]; numbers[i+1] = temp; finished = false; } } } } } class SimpleThreadExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.err.printf("%s: %s at line %d of %s%n", t.getName(), e.toString(), e.getStackTrace()[0].getLineNumber(), e.getStackTrace()[0].getFileName()); } }
blocking queue
public class Producer extends Thread { private BlockingQueue q; private PrintStream out; public Producer(BlockingQueue q, PrintStream out) { setName("Producer"); this.q = q; this.out = out; } public void run() { try { while (true) { q.put(produce()); } } catch (InterruptedException e) { out.printf("%s interrupted: %s", getName(), e.getMessage()); } } private String produce() { while (true) { double r = Math.random(); // Only goes forward 1/10 of the time if ((r*100) < 10) { String s = String.format("Inserted at %tc", new Date()); return s; } } } }
線程池
著名的JUC類庫。
每次提交任務(wù)時,如果線程數(shù)還沒達(dá)到coreSize就創(chuàng)建新線程并綁定該任務(wù)。 所以第coreSize次提交任務(wù)后線程總數(shù)必達(dá)到coreSize,不會重用之前的空閑線程。
線程數(shù)達(dá)到coreSize后,新增的任務(wù)就放到工作隊列里,而線程池里的線程則努力的使用take()從工作隊列里拉活來干。
如果隊列是個有界隊列,又如果線程池里的線程不能及時將任務(wù)取走,工作隊列可能會滿掉,插入任務(wù)就會失敗,此時線程池就會緊急的再創(chuàng)建新的臨時線程來補救。
臨時線程使用poll(keepAliveTime,timeUnit)來從工作隊列拉活,如果時候到了仍然兩手空空沒拉到活,表明它太閑了,就會被解雇掉。
如果core線程數(shù)+臨時線程數(shù) >maxSize,則不能再創(chuàng)建新的臨時線程了,轉(zhuǎn)頭執(zhí)行RejectExecutionHanlder。默認(rèn)的AbortPolicy拋RejectedExecutionException異常,其他選擇包括靜默放棄當(dāng)前任務(wù)(Discard),放棄工作隊列里最老的任務(wù)(DisacardOldest),或由主線程來直接執(zhí)行(CallerRuns),或你自己發(fā)揮想象力寫的一個。
10、其他Arrays
Arrays.sort(myArray); Arrays.toString(myArray) Arrays.binarySearch(myArray, 98) Arrays.deepToString(ticTacToe) Arrays.deepEquals(ticTacToe, ticTacToe3)
Queue
避開集合的add/remove操作,使用offer、poll操作(不拋異常)
Queue q = new LinkedList(); 采用它來實現(xiàn)queue
Override返回類型
支持協(xié)變返回
單線程StringBuilder
線程不安全,在單線程下替換string buffer提高性能
java.lang.instrument
參考New Features and Enhancements J2SE 5.0
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65447.html
摘要:新特性概述系列一安裝及使用系列二運行系列三模塊系統(tǒng)精要系列四更新系列五系列六系列七系列八系列九與的區(qū)別遷移注意事項參數(shù)遷移相關(guān)選項解析使用構(gòu)建實例使用示例帶你提前了解中的新特性 Java語言特性系列 Java5的新特性 Java6的新特性 Java7的新特性 Java8的新特性 Java9的新特性 Java10的新特性 Java11的新特性 Java12的新特性 Java13的新特性...
摘要:為什么需要源語言與虛擬機(jī)存在語義上的差異中方法指的是方法參數(shù)和方法名稱完全一致這樣的操作稱為如果方法參數(shù)類型不一致包括參數(shù)類型或者參數(shù)的順序不一致這樣的操作稱為兩者在中的判斷都不包括返回值類型即返回值類型與兩者無關(guān)中對于同個方法名不同的與都 1.為什么需要bridgeMethod Java(Java源語言)與 JVM 虛擬機(jī) 存在語義上的差異,Java中Override方法指的是方...
摘要:從版本開始,不再單獨發(fā)布或者版本了,有需要的可以自己通過去定制官方解讀官方細(xì)項解讀穩(wěn)步推進(jìn)系列六的小試牛刀一文讀懂的為何如此高效棄用引擎 Java語言特性系列 Java5的新特性 Java6的新特性 Java7的新特性 Java8的新特性 Java9的新特性 Java10的新特性 Java11的新特性 Java12的新特性 Java13的新特性 序 本文主要講述一下Java11的新...
閱讀 2908·2021-11-25 09:43
閱讀 2328·2021-11-24 09:39
閱讀 2717·2021-09-23 11:51
閱讀 1407·2021-09-07 10:11
閱讀 1455·2019-08-27 10:52
閱讀 1937·2019-08-26 12:13
閱讀 3359·2019-08-26 11:57
閱讀 1399·2019-08-26 11:31