Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java, Up to Date Sources

Source codes of the Presentation "Java, Up to Date", http://www.slideshare.net/akirakoyasu/java-up-to-date

Related Books

Free with a 30 day trial from Scribd

See all
  • Be the first to comment

  • Be the first to like this

Java, Up to Date Sources

  1. 1. Java, Up to Date Sources Copyright © 2012 Akira Koyasu Some rights reserved.
  2. 2. StringInSwitch.java 1 p a c k a g e java7.coin; 2 3 p u b l i c c l a s s StringInSwitch { 4 5 p u b l i c s t a t i c v o i d main(String[] args) { 6 String flag = "aaa"; 7 s w i t c h (flag) { 8 c a s e "aaa": 9 System. out .println("aaa");10 break;11 c a s e "bbb":12 System. out .println("bbb");13 break;14 c a s e "ccc":15 System. out .println("ccc");16 break;17 }18 }19 }20 11
  3. 3. NumericLiteral.java 1 p a c k a g e java7.coin; 2 3 p u b l i c c l a s s NumericLiteral { 4 5 p u b l i c s t a t i c v o i d main(String[] args) { 6 i n t b = 0b1110; // binary (new!) 7 8 i n t o = 016; // octal 9 i n t d = 14; // decimal10 i n t x = 0xE; // hexadecimal1112 System. out .println(b);13 System. out .println(o);14 System. out .println(d);15 System. out .println(x);1617 i n t m = 1_000_000;18 System. out .println(m);19 }20 }212
  4. 4. Bond.java 1 p a c k a g e java7.coin; 2 3 p u b l i c c l a s s Bond { 4 p u b l i c s t a t i c v o i d main(String[] args) { 5 // Courtesy Josh Bloch 6 i n t bond = 7 0000_____________0000________0000000000000000__000000000000000000+ 8 00000000_________00000000______000000000000000__0000000000000000000+ 9 000____000_______000____000_____000_______0000__00______0+10 000______000_____000______000_____________0000___00______0+11 0000______0000___0000______0000___________0000_____0_____0+12 0000______0000___0000______0000__________0000___________0+13 0000______0000___0000______0000_________0000__0000000000+14 0000______0000___0000______0000________0000+15 000______000_____000______000________0000+16 000____000_______000____000________00000+17 00000000_________00000000_______0000000+18 0000_____________0000________000000007;1920 System. out .println(bond);21 }22 }233
  5. 5. MultiCatch.java 1 p a c k a g e java7.coin; 2 3 i m p o r t java7.coin.exception.Exception1; 8 9 p u b l i c c l a s s MultiCatch {1011 v o i d callFoo() {12 try {13 foo (); // throws Exception1, Exception214 } c a t c h (Exception1 | Exception2 e) {15 e.printStackTrace();16 }17 }1819 v o i d callBar() t h r o w s SubException1, SubException2 {20 try {21 bar (); // throws SubException1, SubException222 } c a t c h (SuperException e) {23 t h r o w e;24 }25 }2627 s t a t i c v o i d foo() t h r o w s Exception1, Exception2 {28 }2930 s t a t i c v o i d bar() t h r o w s SubException1, SubException2 {31 }32 }334
  6. 6. TryWithResources.java 1 p a c k a g e java7.coin; 2 3 i m p o r t java.io.File; 7 8 p u b l i c c l a s s TryWithResources { 910 p u b l i c s t a t i c v o i d main(String[] args) {11 File file = n e w File("/path/to/file");12 t r y (Writer writer = n e w FileWriter(file)) {13 writer.write("hello!!");14 } c a t c h (IOException e) {15 e.printStackTrace();16 }17 }18 }195
  7. 7. Diamond.java 1 p a c k a g e java7.coin; 2 3 i m p o r t java.util.ArrayList; 7 8 p u b l i c c l a s s Diamond { 910 p u b l i c s t a t i c v o i d main(String[] args) {11 @SuppressWarnings("unused")12 Map<String, List<Integer>> map = n e w HashMap<>();13 }1415 v o i d anonymous() {16 // <> cannot be used with anonymous classes17 List<String> list = n e w ArrayList<>() {}; // 匿名クラス18 }1920 v o i d call() {21 // The method doSomething(List<String>) in the type Diamond22 // is not applicable for the arguments (ArrayList<Object>)23 doSomething(n e w ArrayList<>()); // メソッド呼び出し n2425 doOtherthing(n e w ArrayList<>()); n26 }2728 v o i d doSomething(List<String> list) {29 }3031 v o i d doOtherthing(List<Object> list) {32 }33 }346
  8. 8. Varargs.java 1 p a c k a g e java7.coin; 2 3 i m p o r t java.util.Arrays; 5 6 p u b l i c c l a s s Varargs { 7 8 p u b l i c s t a t i c v o i d main(String[] args) { 9 List<String> b = Arrays. asList ("taro", "jiro", "saburo");10 List<String> s = Arrays. asList ("haruko", "natsuko", "akiko");11 // Type safety: A generic array of List<String>12 // is created for a varargs parameter13 pol (b, s);14 notPol (b, s);15 }1617 // Type safety: Potential heap pollution18 // via varargs parameter strLists19 s t a t i c v o i d pol(List<String>... strLists) {20 // ...21 }2223 @SafeVarargs24 s t a t i c v o i d notPol(List<String>... strLists) {25 // ...26 }27 }287
  9. 9. MergeSortSimple.java 1 p a c k a g e java7.forkjoin; 2 3 i m p o r t java.util.Arrays; 6 7 p u b l i c c l a s s MergeSortSimple { 8 9 p u b l i c s t a t i c v o i d main(String[] args) {10 Stopwatch stopwatch = n e w Stopwatch();1112 // ランダムなint配列13 f i n a l i n t SIZE = 100_000_000;14 i n t [] ints = n e w i n t [SIZE];15 f o r (i n t i = 0; i < SIZE; i++) { i16 ints[i] = (i n t ) (Math. random () * 100_000); i17 }18 System. out .println("head: " + Arrays. toString (Arys. head (ints)));19 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));2021 stopwatch.start();22 ints = sort (ints);23 stopwatch.stop();2425 System. out .println("head: " + Arrays. toString (Arys. head (ints)));26 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));27 System. out .println("time: " + stopwatch);28 }2930 s t a t i c i n t [] sort(i n t [] ints) { i31 i f (ints.length <= 2) {32 r e t u r n sortDirect (ints);33 } else {34 i n t mid = (i n t ) (ints.length * 0.5); i35 i n t [] left = sort (Arrays. copyOf (ints, mid));36 i n t [] right = sort (Arrays. copyOfRange (ints, mid, ints.length));37 r e t u r n merge (left, right);38 }39 }4041 s t a t i c i n t [] sortDirect(i n t [] ints) { i42 i f (ints.length <= 1) {43 r e t u r n ints;44 } e l s e i f (ints.length == 2) {45 i f (ints[0] > ints[1]) {46 i n t g = ints[0];47 ints[0] = ints[1];48 ints[1] = g;49 }50 r e t u r n ints;51 }52 t h r o w n e w AssertionError();53 }5455 s t a t i c i n t [] merge(i n t [] left, i n t [] right) { i56 i n t [] all = n e w i n t [left.length + right.length];5758 f o r (i n t i = 0, j = 0, k = 0; i < all.length; i++) { i59 i f (j < left.length && k < right.length) {60 i n t l = left[j];61 i n t r = right[k];62 i f (l < r) {63 all[i] = l;64 j++;65 } else {66 all[i] = r;67 k++;68 }69 } e l s e i f (j < left.length) {70 all[i] = left[j];8
  10. 10. MergeSortSimple.java71 j++;72 } e l s e i f (k < right.length) {73 all[i] = right[k];74 k++;75 } else {76 t h r o w n e w AssertionError();77 }78 }7980 r e t u r n all;81 }82 }839
  11. 11. MergeSortByForkJoin.java 1 p a c k a g e java7.forkjoin; 2 3 i m p o r t java.util.Arrays; 8 9 p u b l i c c l a s s MergeSortByForkJoin {1011 p u b l i c s t a t i c v o i d main(String[] args) {12 Stopwatch stopwatch = n e w Stopwatch();13 ForkJoinPool pool = n e w ForkJoinPool();1415 // ランダムなint配列16 f i n a l i n t SIZE = 100_000_000;17 i n t [] ints = n e w i n t [SIZE];18 f o r (i n t i = 0; i < SIZE; i++) { i19 ints[i] = (i n t ) (Math. random () * 100_000); i20 }21 System. out .println("head: " + Arrays. toString (Arys. head (ints)));22 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));2324 stopwatch.start();25 ints = pool.invoke(n e w MergeSort(ints)); n26 stopwatch.stop();2728 System. out .println("head: " + Arrays. toString (Arys. head (ints)));29 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));30 System. out .println("time: " + stopwatch);31 }3233 s t a t i c c l a s s MergeSort e x t e n d s RecursiveTask<i n t []> { i34 p r i v a t e s t a t i c f i n a l l o n g serialVersionUID = 1L;3536 i n t [] ints;3738 MergeSort(i n t [] ints) { i39 t h i s .ints = ints;40 }4142 @Override43 p r o t e c t e d i n t [] compute() {44 i f (ints.length <= 2) {45 r e t u r n MergeSortSimple. sortDirect (ints);46 } else {47 i n t mid = (i n t ) (ints.length * 0.5); i48 MergeSort leftSort = n e w MergeSort(Arrays. copyOf (ints, mid));49 MergeSort rightSort = n e w MergeSort(Arrays. copyOfRange (ints, mid, ints.length));50 leftSort.fork();51 i n t [] right = rightSort.compute();52 i n t [] left = leftSort.join();53 r e t u r n MergeSortSimple. merge (left, right);54 }55 }56 }57 }5810
  12. 12. MergeSortByExecutor.java 1 p a c k a g e java7.forkjoin; 2 3 i m p o r t java.util.Arrays;1415 p u b l i c c l a s s MergeSortByExecutor {1617 s t a t i c f i n a l i n t pros = Runtime. getRuntime ().availableProcessors();18 s t a t i c f i n a l ExecutorService executor = Executors. newFixedThreadPool ( pros );1920 p u b l i c s t a t i c v o i d main(String[] args) {21 Stopwatch stopwatch = n e w Stopwatch();2223 // ランダムなint配列24 f i n a l i n t SIZE = 100_000_000;25 i n t [] ints = n e w i n t [SIZE];26 f o r (i n t i = 0; i < SIZE; i++) { i27 ints[i] = (i n t ) (Math. random () * 100_000); i28 }29 System. out .println("head: " + Arrays. toString (Arys. head (ints)));30 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));3132 stopwatch.start();33 ints = divide (ints);34 stopwatch.stop();3536 System. out .println("head: " + Arrays. toString (Arys. head (ints)));37 System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));38 System. out .println("time: " + stopwatch);3940 executor .shutdown();41 }4243 s t a t i c i n t [] divide(f i n a l i n t [] ints) { f44 List<Future<i n t []>> futureList = Lists. newArrayList (); i45 f i n a l i n t len = ints.length / pros ;46 i n t i = 0;47 f o r (; i < pros ; i++) {48 f i n a l i n t fi = i;49 futureList.add( executor .submit(n e w Callable<i n t []>() { n i50 @Override51 p u b l i c i n t [] call() t h r o w s Exception {52 r e t u r n MergeSortSimple. sort (Arrays. copyOfRange (ints, fi * len, (fi+1) * len));53 }}));54 }55 f i n a l i n t fi = i;56 futureList.add( executor .submit(n e w Callable<i n t []>() { n i57 @Override58 p u b l i c i n t [] call() t h r o w s Exception {59 r e t u r n MergeSortSimple. sort (Arrays. copyOfRange (ints, fi * len, ints.length));60 }}));6162 try {63 Iterator<Future<i n t []>> itr = futureList.iterator(); i64 i n t [] left = itr.next().get();65 w h i l e (itr.hasNext()) {66 i n t [] right = itr.next().get();67 left = MergeSortSimple. merge (left, right);68 }69 r e t u r n left;70 } c a t c h (InterruptedException | ExecutionException e) {71 e.printStackTrace();72 }73 t h r o w n e w AssertionError();74 }75 }7611
  13. 13. BasicUse.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.BufferedWriter;1112 p u b l i c c l a s s BasicUse {1314 p u b l i c s t a t i c v o i d main(String[] args) {15 FileSystem fs = FileSystems. getDefault ();16 Path path = fs.getPath("/path", "to", "file");1718 t r y (BufferedWriter bw = Files. newBufferedWriter (path,19 StandardCharsets. UTF_8 , StandardOpenOption. CREATE )) {2021 bw.write("Oh, NIO.2 !!");2223 } c a t c h (IOException e) {24 e.printStackTrace();25 }26 }27 }2812
  14. 14. FilesSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException; 910 p u b l i c c l a s s FilesSample {1112 p u b l i c s t a t i c v o i d main(String[] args) {13 Path dir = Paths. get ("/path", "to");14 Path path1 = Paths. get ("/path", "to", "file1");15 Path path2 = Paths. get ("/path", "to", "file2");16 Path link = Paths. get ("/path", "to", "link");1718 try {19 Files. createFile (path1);20 Files. createSymbolicLink (link, path1);21 Files. copy (path1, path2, StandardCopyOption. COPY_ATTRIBUTES );22 Files. move (path1, path2, StandardCopyOption. ATOMIC_MOVE );23 @SuppressWarnings("unused")24 b y t e [] bytes = Files. readAllBytes (path2);2526 t r y (DirectoryStream<Path> ds = Files. newDirectoryStream (dir)) {27 f o r (Path path : ds) {28 System. out .println(path);29 }30 }31 } c a t c h (IOException e) {32 e.printStackTrace();33 }34 }35 }3613
  15. 15. AttributeViewSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException;1112 p u b l i c c l a s s AttributeViewSample {1314 p u b l i c s t a t i c v o i d main(String[] args) {15 Path path = Paths. get ("/path", "to", "file");16 BasicFileAttributeView view17 = Files. getFileAttributeView (path, BasicFileAttributeView.c l a s s ); c18 PosixFileAttributeView view219 = Files. getFileAttributeView (path, PosixFileAttributeView.c l a s s ); c20 try {21 i f (view != n u l l ) {22 BasicFileAttributes attributes = view.readAttributes();23 System. out .println(attributes.creationTime());24 System. out .println(attributes.lastModifiedTime());25 System. out .println(attributes.lastAccessTime());26 }27 i f (view2 != n u l l ) {28 PosixFileAttributes attributes2 = view2.readAttributes();29 System. out .println(attributes2.owner());30 System. out .println(attributes2.group());31 System. out .println(attributes2.permissions());32 }33 } c a t c h (IOException e) {34 e.printStackTrace();35 }36 }37 }3814
  16. 16. FileVisitorSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException;1011 p u b l i c c l a s s FileVisitorSample {1213 p u b l i c s t a t i c v o i d main(String[] args) {14 try {15 Path dir = Paths. get ("/path", "to", "dir");16 Files. walkFileTree (dir, n e w SimpleFileVisitor<Path>() {17 @Override18 p u b l i c FileVisitResult preVisitDirectory(Path dir,19 BasicFileAttributes attrs) t h r o w s IOException {20 System. out .println("preVisitDir: " + dir);21 r e t u r n FileVisitResult. CONTINUE ;22 }2324 @Override25 p u b l i c FileVisitResult postVisitDirectory(Path dir,26 IOException exc) t h r o w s IOException {27 System. out .println("postVisitDir: " + dir);28 r e t u r n FileVisitResult. CONTINUE ;29 }3031 @Override32 p u b l i c FileVisitResult visitFile(Path file,33 BasicFileAttributes attrs) t h r o w s IOException {34 System. out .println("visitFile: " + file);35 r e t u r n FileVisitResult. CONTINUE ;36 }37 });38 } c a t c h (IOException e) {39 e.printStackTrace();40 }41 }42 }4315
  17. 17. WatchServiceSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException;1112 p u b l i c c l a s s WatchServiceSample {1314 p u b l i c s t a t i c v o i d main(String[] args) {15 FileSystem fs = FileSystems. getDefault ();16 Path dir = fs.getPath("/path", "to", "dir");17 try {18 WatchService watcher = fs.newWatchService();19 dir.register(watcher,20 StandardWatchEventKinds. ENTRY_CREATE ,21 StandardWatchEventKinds. ENTRY_MODIFY ,22 StandardWatchEventKinds. ENTRY_DELETE );23 b o o l e a n valid;24 do {25 WatchKey key = watcher.take(); // ブロック26 f o r (WatchEvent<?> event : key.pollEvents()) {27 i f (event.kind() == StandardWatchEventKinds. OVERFLOW ) {28 System. out .println("overflow!!");29 } else {30 System. out .println(31 event.kind() + " : " + event.context());32 }33 }34 valid = key.reset();35 } w h i l e (valid);36 } c a t c h (IOException | InterruptedException e) {37 e.printStackTrace();38 }39 }40 }4116
  18. 18. AsynchronousSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.FileInputStream;1516 p u b l i c c l a s s AsynchronousSample {1718 p u b l i c s t a t i c v o i d main(String[] args) {19 t r y (InputStream in = n e w FileInputStream(20 "/path/to/largeFile");) {21 write (in).await();22 } c a t c h (IOException | InterruptedException e) {23 e.printStackTrace();24 }25 }2627 s t a t i c CountDownLatch write(InputStream in) {28 ReadableByteChannel rbc = Channels. newChannel (in);29 ByteBuffer buf = ByteBuffer. allocate (0x1000);3031 Path file = Paths. get ("/path", "to", "file");32 CountDownLatch latch = n e w CountDownLatch(1);33 try {34 AsynchronousFileChannel afc =35 AsynchronousFileChannel. open (file,36 StandardOpenOption. CREATE ,37 StandardOpenOption. WRITE );38 i n t len;39 i f ((len = rbc.read(buf)) > -1) {40 buf.flip();41 afc.write(buf, 0, buf, n e w WriteContinuing(rbc, afc, len, latch));42 }43 } c a t c h (IOException e) {44 e.printStackTrace();45 latch.countDown();46 }47 r e t u r n latch;48 }4950 s t a t i c c l a s s WriteContinuing i m p l e m e n t s CompletionHandler<Integer, ByteBuffer> {51 p r i v a t e f i n a l ReadableByteChannel rbc;52 p r i v a t e f i n a l AsynchronousFileChannel afc;53 p r i v a t e f i n a l i n t pos;54 p r i v a t e f i n a l CountDownLatch latch;5556 p u b l i c WriteContinuing(57 ReadableByteChannel rbc,58 AsynchronousFileChannel afc,59 i n t position,60 CountDownLatch latch) {61 t h i s .rbc = rbc;62 t h i s .afc = afc;63 t h i s .pos = position;64 t h i s .latch = latch;65 }6667 @Override68 p u b l i c v o i d completed(Integer result, ByteBuffer buf) {69 buf.clear();70 try{71 i n t len;72 i f ((len = rbc.read(buf)) > -1) {73 buf.flip();74 afc.write(buf, pos, buf, n e w WriteContinuing(rbc, afc, pos + len, latch));75 } else {76 System. out .println("completed!");77 afc.close();78 latch.countDown();79 }17
  19. 19. AsynchronousSample.java80 } c a t c h (IOException e) {81 e.printStackTrace();82 latch.countDown();83 }84 }8586 @Override87 p u b l i c v o i d failed(Throwable exc, ByteBuffer buf) {88 exc.printStackTrace();89 }90 }91 }9218
  20. 20. Puzzle.java 1 p a c k a g e java7.puzzle; 2 3 i m p o r t java.util.Arrays; 5 6 p u b l i c c l a s s Puzzle { 7 8 p u b l i c s t a t i c v o i d main(String[] args) { 9 List<String>[] stringLists = n e w List<String>[10];10 stringLists[0] = Arrays. asList ("first string!");11 Object[] array = stringLists;12 array[0] = Arrays. asList (0);13 System. out .println(stringLists[0].get(0));14 }15 }1619
  21. 21. index.xhtml 1 <?xml version= "1.0" encoding= "UTF-8" ?> 2 <!DOCTYPE html> 3 <html xmlns:h= "http://java.sun.com/jsf/html" > 4 <head> 5 <title>Greeting</title> 6 </head> 7 <h:body> 8 #{myBean.greeting} 9 </h:body>10 </html>20
  22. 22. MyBean.java 1 2 3 i m p o r t javax.inject.Inject; 5 6 @Named 7 p u b l i c c l a s s MyBean { 8 @Inject 9 p r i v a t e MyService myService;1011 p u b l i c String getGreeting() {12 r e t u r n myService.getGreeting();13 }14 }1521
  23. 23. MyService.java 1 2 3 i m p o r t javax.annotation.ManagedBean; 4 5 @ManagedBean 6 p u b l i c c l a s s MyService { 7 p u b l i c String getGreeting() { 8 r e t u r n "Hello JavaEE6!!"; 9 }10 }1122
  24. 24. beans.xml123
  25. 25. faces-config.xml124
  26. 26. NotesThis work is licensed under the Creative Commons Attribution-NonCommercial 3.0 UnportedLicense. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/. 25

×