SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Java, Up to Date
    Sources




        Copyright © 2012 Akira Koyasu Some rights reserved.
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    1




1
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;                // decimal
10                 i n t x = 0xE;               // hexadecimal
11
12                 System. out .println(b);
13                 System. out .println(o);
14                 System. out .println(d);
15                 System. out .println(x);
16
17                 i n t m = 1_000_000;
18                 System. out .println(m);
19         }
20 }
21




2
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;
19
20                 System. out .println(bond);
21         }
22 }
23




3
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 {
10
11        v o i d callFoo() {
12               try {
13                     foo (); // throws Exception1, Exception2
14               } c a t c h (Exception1 | Exception2 e) {
15                     e.printStackTrace();
16               }
17        }
18
19        v o i d callBar() t h r o w s SubException1, SubException2 {
20               try {
21                     bar (); // throws SubException1, SubException2
22               } c a t c h (SuperException e) {
23                     t h r o w e;
24               }
25        }
26
27        s t a t i c v o i d foo() t h r o w s Exception1, Exception2 {
28        }
29
30        s t a t i c v o i d bar() t h r o w s SubException1, SubException2 {
31        }
32   }
33




4
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 {
 9
10        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   }
19




5
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 {
 9
10         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         }
14
15         v o i d anonymous() {
16                 // '<>' cannot be used with anonymous classes
17                 List<String> list = n e w ArrayList<>() {}; // 匿名クラス
18     }
19
20     v o i d call() {
21            // The method doSomething(List<String>) in the type Diamond
22            // is not applicable for the arguments (ArrayList<Object>)
23            doSomething(n e w ArrayList<>()); // メソッド呼び出し
                          n
24
25         doOtherthing(n e w ArrayList<>());
                        n
26     }
27
28     v o i d doSomething(List<String> list) {
29     }
30
31     v o i d doOtherthing(List<Object> list) {
32     }
33 }
34




6
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 parameter
13                pol (b, s);
14                notPol (b, s);
15        }
16
17        // Type safety: Potential heap pollution
18        // via varargs parameter strLists
19        s t a t i c v o i d pol(List<String>... strLists) {
20                // ...
21        }
22
23        @SafeVarargs
24        s t a t i c v o i d notPol(List<String>... strLists) {
25                // ...
26        }
27   }
28




7
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();
11
12                 // ランダムな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++) {
                      i
16                   ints[i] = (i n t ) (Math. random () * 100_000);
                                  i
17           }
18           System. out .println("head: " + Arrays. toString (Arys. head (ints)));
19           System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));
20
21           stopwatch.start();
22           ints = sort (ints);
23           stopwatch.stop();
24
25           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      }
29
30      s t a t i c i n t [] sort(i n t [] ints) {
                                     i
31              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);
                                       i
35                    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      }
40
41      s t a t i c i n t [] sortDirect(i n t [] ints) {
                                              i
42              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      }
54
55      s t a t i c i n t [] merge(i n t [] left, i n t [] right) {
                                    i
56              i n t [] all = n e w i n t [left.length + right.length];
57
58           f o r (i n t i = 0, j = 0, k = 0; i < all.length; i++) {
                     i
59                 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
MergeSortSimple.java

71                    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         }
79
80         r e t u r n all;
81     }
82 }
83




9
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 {
10
11         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();
14
15                 // ランダムな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++) {
                      i
19                   ints[i] = (i n t ) (Math. random () * 100_000);
                                  i
20           }
21           System. out .println("head: " + Arrays. toString (Arys. head (ints)));
22           System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));
23
24           stopwatch.start();
25           ints = pool.invoke(n e w MergeSort(ints));
                                n
26           stopwatch.stop();
27
28           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      }
32
33      s t a t i c c l a s s MergeSort e x t e n d s RecursiveTask<i n t []> {
                                                                           i
34              p r i v a t e s t a t i c f i n a l l o n g serialVersionUID = 1L;
35
36           i n t [] ints;
37
38           MergeSort(i n t [] ints) {
                           i
39               t h i s .ints = ints;
40           }
41
42           @Override
43           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);
                                             i
48                           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 }
58




10
MergeSortByExecutor.java

 1 p a c k a g e java7.forkjoin;
 2
 3 i m p o r t java.util.Arrays;
14
15 p u b l i c c l a s s MergeSortByExecutor {
16
17         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 );
19
20         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();
22
23                 // ランダムな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++) {
                     i
27                  ints[i] = (i n t ) (Math. random () * 100_000);
                                 i
28          }
29          System. out .println("head: " + Arrays. toString (Arys. head (ints)));
30          System. out .println("tail: " + Arrays. toString (Arys. tail (ints)));
31
32          stopwatch.start();
33          ints = divide (ints);
34          stopwatch.stop();
35
36          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);
39
40          executor .shutdown();
41     }
42
43     s t a t i c i n t [] divide(f i n a l i n t [] ints) {
                                               f
44             List<Future<i n t []>> futureList = Lists. newArrayList ();
                                       i
45             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           i
50                             @Override
51                             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              i
57                     @Override
58                     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                     }}));
61
62          try {
63                  Iterator<Future<i n t []>> itr = futureList.iterator();
                                           i
64                  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 }
76




11
BasicUse.java

 1   p a c k a g e java7.nio2;
 2
 3   i m p o r t java.io.BufferedWriter;
11
12   p u b l i c c l a s s BasicUse {
13
14        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");
17
18              t r y (BufferedWriter bw = Files. newBufferedWriter (path,
19                        StandardCharsets. UTF_8 , StandardOpenOption. CREATE )) {
20
21                   bw.write("Oh, NIO.2 !!");
22
23              } c a t c h (IOException e) {
24                    e.printStackTrace();
25              }
26        }
27   }
28




12
FilesSample.java

 1   p a c k a g e java7.nio2;
 2
 3   i m p o r t java.io.IOException;
 9
10   p u b l i c c l a s s FilesSample {
11
12        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");
17
18             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);
25
26                   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   }
36




13
AttributeViewSample.java

 1   p a c k a g e java7.nio2;
 2
 3   i m p o r t java.io.IOException;
11
12   p u b l i c c l a s s AttributeViewSample {
13
14        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 view
17                      = Files. getFileAttributeView (path, BasicFileAttributeView.c l a s s );
                                                                                      c
18                PosixFileAttributeView view2
19                      = Files. getFileAttributeView (path, PosixFileAttributeView.c l a s s );
                                                                                      c
20                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   }
38




14
FileVisitorSample.java

 1   p a c k a g e java7.nio2;
 2
 3   i m p o r t java.io.IOException;
10
11   p u b l i c c l a s s FileVisitorSample {
12
13        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                              @Override
18                              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                              }
23
24                        @Override
25                        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                        }
30
31                        @Override
32                        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   }
43




15
WatchServiceSample.java

 1 p a c k a g e java7.nio2;
 2
 3 i m p o r t java.io.IOException;
11
12 p u b l i c c l a s s WatchServiceSample {
13
14         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 }
41




16
AsynchronousSample.java

 1 p a c k a g e java7.nio2;
 2
 3 i m p o r t java.io.FileInputStream;
15
16 p u b l i c c l a s s AsynchronousSample {
17
18         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         }
26
27         s t a t i c CountDownLatch write(InputStream in) {
28                 ReadableByteChannel rbc = Channels. newChannel (in);
29                 ByteBuffer buf = ByteBuffer. allocate (0x1000);
30
31                 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         }
49
50         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;
55
56                 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                 }
66
67                 @Override
68                 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
AsynchronousSample.java

80             } c a t c h (IOException e) {
81                   e.printStackTrace();
82                   latch.countDown();
83             }
84         }
85
86         @Override
87         p u b l i c v o i d failed(Throwable exc, ByteBuffer buf) {
88                 exc.printStackTrace();
89         }
90     }
91 }
92




18
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   }
16




19
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
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;
10
11        p u b l i c String getGreeting() {
12                r e t u r n myService.getGreeting();
13        }
14   }
15




21
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   }
11




22
beans.xml

1




23
faces-config.xml

1




24
Notes




This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported
License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/.




  25

Contenu connexe

Tendances

The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
jeffz
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
mickey24
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
jeffz
 

Tendances (20)

ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему кодуITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
ITGM #9 - Коварный CodeType, или от segfault'а к работающему коду
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
Cilk Plus Parallel Reduction
Cilk Plus Parallel ReductionCilk Plus Parallel Reduction
Cilk Plus Parallel Reduction
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
 
第二回CTF勉強会資料
第二回CTF勉強会資料第二回CTF勉強会資料
第二回CTF勉強会資料
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsReverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 

En vedette (6)

Доржханд14, Эцэг эхийн оролцоо
Доржханд14, Эцэг эхийн оролцооДоржханд14, Эцэг эхийн оролцоо
Доржханд14, Эцэг эхийн оролцоо
 
Tokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo TyrantTokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo Tyrant
 
Heavy metal poisoning
Heavy metal poisoningHeavy metal poisoning
Heavy metal poisoning
 
PHP conference 2013 ja report
PHP conference 2013 ja reportPHP conference 2013 ja report
PHP conference 2013 ja report
 
Доржханд14.Э.э ийн сх-лэх хичээл
Доржханд14.Э.э ийн сх-лэх хичээлДоржханд14.Э.э ийн сх-лэх хичээл
Доржханд14.Э.э ийн сх-лэх хичээл
 
Java, Up to Date
Java, Up to DateJava, Up to Date
Java, Up to Date
 

Similaire à Java, Up to Date Sources

Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
GkhanGirgin3
 

Similaire à Java, Up to Date Sources (20)

C arrays
C arraysC arrays
C arrays
 
Vcs16
Vcs16Vcs16
Vcs16
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
C program
C programC program
C program
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
1z0 851 exam-java standard edition 6 programmer certified professional
1z0 851 exam-java standard edition 6 programmer certified professional1z0 851 exam-java standard edition 6 programmer certified professional
1z0 851 exam-java standard edition 6 programmer certified professional
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Marat-Slides
Marat-SlidesMarat-Slides
Marat-Slides
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and Polynomial
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Arrays
ArraysArrays
Arrays
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 

Plus de 輝 子安

Plus de 輝 子安 (10)

Protractor under the hood
Protractor under the hoodProtractor under the hood
Protractor under the hood
 
そろそろLambda(CI/CD編)
そろそろLambda(CI/CD編)そろそろLambda(CI/CD編)
そろそろLambda(CI/CD編)
 
Dockerで構成するWebサービス 〜EmotionTechの場合〜
Dockerで構成するWebサービス 〜EmotionTechの場合〜Dockerで構成するWebサービス 〜EmotionTechの場合〜
Dockerで構成するWebサービス 〜EmotionTechの場合〜
 
Workshop: Docker on Elastic Beanstalk
Workshop: Docker on Elastic BeanstalkWorkshop: Docker on Elastic Beanstalk
Workshop: Docker on Elastic Beanstalk
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Garbage Collection for Dummies
Garbage Collection for DummiesGarbage Collection for Dummies
Garbage Collection for Dummies
 
JavaOne Guide for the Petite Bourgeoisie
JavaOne Guide for the Petite BourgeoisieJavaOne Guide for the Petite Bourgeoisie
JavaOne Guide for the Petite Bourgeoisie
 
Java, Moving Forward
Java, Moving ForwardJava, Moving Forward
Java, Moving Forward
 
Hello, Guava ! samples
Hello, Guava ! samplesHello, Guava ! samples
Hello, Guava ! samples
 
Hello, Guava !
Hello, Guava !Hello, Guava !
Hello, Guava !
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Java, Up to Date Sources

  • 1. Java, Up to Date Sources Copyright © 2012 Akira Koyasu Some rights reserved.
  • 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 1 1
  • 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; // decimal 10 i n t x = 0xE; // hexadecimal 11 12 System. out .println(b); 13 System. out .println(o); 14 System. out .println(d); 15 System. out .println(x); 16 17 i n t m = 1_000_000; 18 System. out .println(m); 19 } 20 } 21 2
  • 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; 19 20 System. out .println(bond); 21 } 22 } 23 3
  • 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 { 10 11 v o i d callFoo() { 12 try { 13 foo (); // throws Exception1, Exception2 14 } c a t c h (Exception1 | Exception2 e) { 15 e.printStackTrace(); 16 } 17 } 18 19 v o i d callBar() t h r o w s SubException1, SubException2 { 20 try { 21 bar (); // throws SubException1, SubException2 22 } c a t c h (SuperException e) { 23 t h r o w e; 24 } 25 } 26 27 s t a t i c v o i d foo() t h r o w s Exception1, Exception2 { 28 } 29 30 s t a t i c v o i d bar() t h r o w s SubException1, SubException2 { 31 } 32 } 33 4
  • 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 { 9 10 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 } 19 5
  • 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 { 9 10 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 } 14 15 v o i d anonymous() { 16 // '<>' cannot be used with anonymous classes 17 List<String> list = n e w ArrayList<>() {}; // 匿名クラス 18 } 19 20 v o i d call() { 21 // The method doSomething(List<String>) in the type Diamond 22 // is not applicable for the arguments (ArrayList<Object>) 23 doSomething(n e w ArrayList<>()); // メソッド呼び出し n 24 25 doOtherthing(n e w ArrayList<>()); n 26 } 27 28 v o i d doSomething(List<String> list) { 29 } 30 31 v o i d doOtherthing(List<Object> list) { 32 } 33 } 34 6
  • 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 parameter 13 pol (b, s); 14 notPol (b, s); 15 } 16 17 // Type safety: Potential heap pollution 18 // via varargs parameter strLists 19 s t a t i c v o i d pol(List<String>... strLists) { 20 // ... 21 } 22 23 @SafeVarargs 24 s t a t i c v o i d notPol(List<String>... strLists) { 25 // ... 26 } 27 } 28 7
  • 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(); 11 12 // ランダムな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++) { i 16 ints[i] = (i n t ) (Math. random () * 100_000); i 17 } 18 System. out .println("head: " + Arrays. toString (Arys. head (ints))); 19 System. out .println("tail: " + Arrays. toString (Arys. tail (ints))); 20 21 stopwatch.start(); 22 ints = sort (ints); 23 stopwatch.stop(); 24 25 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 } 29 30 s t a t i c i n t [] sort(i n t [] ints) { i 31 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); i 35 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 } 40 41 s t a t i c i n t [] sortDirect(i n t [] ints) { i 42 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 } 54 55 s t a t i c i n t [] merge(i n t [] left, i n t [] right) { i 56 i n t [] all = n e w i n t [left.length + right.length]; 57 58 f o r (i n t i = 0, j = 0, k = 0; i < all.length; i++) { i 59 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. MergeSortSimple.java 71 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 } 79 80 r e t u r n all; 81 } 82 } 83 9
  • 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 { 10 11 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(); 14 15 // ランダムな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++) { i 19 ints[i] = (i n t ) (Math. random () * 100_000); i 20 } 21 System. out .println("head: " + Arrays. toString (Arys. head (ints))); 22 System. out .println("tail: " + Arrays. toString (Arys. tail (ints))); 23 24 stopwatch.start(); 25 ints = pool.invoke(n e w MergeSort(ints)); n 26 stopwatch.stop(); 27 28 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 } 32 33 s t a t i c c l a s s MergeSort e x t e n d s RecursiveTask<i n t []> { i 34 p r i v a t e s t a t i c f i n a l l o n g serialVersionUID = 1L; 35 36 i n t [] ints; 37 38 MergeSort(i n t [] ints) { i 39 t h i s .ints = ints; 40 } 41 42 @Override 43 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); i 48 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 } 58 10
  • 12. MergeSortByExecutor.java 1 p a c k a g e java7.forkjoin; 2 3 i m p o r t java.util.Arrays; 14 15 p u b l i c c l a s s MergeSortByExecutor { 16 17 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 ); 19 20 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(); 22 23 // ランダムな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++) { i 27 ints[i] = (i n t ) (Math. random () * 100_000); i 28 } 29 System. out .println("head: " + Arrays. toString (Arys. head (ints))); 30 System. out .println("tail: " + Arrays. toString (Arys. tail (ints))); 31 32 stopwatch.start(); 33 ints = divide (ints); 34 stopwatch.stop(); 35 36 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); 39 40 executor .shutdown(); 41 } 42 43 s t a t i c i n t [] divide(f i n a l i n t [] ints) { f 44 List<Future<i n t []>> futureList = Lists. newArrayList (); i 45 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 i 50 @Override 51 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 i 57 @Override 58 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 }})); 61 62 try { 63 Iterator<Future<i n t []>> itr = futureList.iterator(); i 64 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 } 76 11
  • 13. BasicUse.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.BufferedWriter; 11 12 p u b l i c c l a s s BasicUse { 13 14 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"); 17 18 t r y (BufferedWriter bw = Files. newBufferedWriter (path, 19 StandardCharsets. UTF_8 , StandardOpenOption. CREATE )) { 20 21 bw.write("Oh, NIO.2 !!"); 22 23 } c a t c h (IOException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 12
  • 14. FilesSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException; 9 10 p u b l i c c l a s s FilesSample { 11 12 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"); 17 18 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); 25 26 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 } 36 13
  • 15. AttributeViewSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException; 11 12 p u b l i c c l a s s AttributeViewSample { 13 14 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 view 17 = Files. getFileAttributeView (path, BasicFileAttributeView.c l a s s ); c 18 PosixFileAttributeView view2 19 = Files. getFileAttributeView (path, PosixFileAttributeView.c l a s s ); c 20 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 } 38 14
  • 16. FileVisitorSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException; 10 11 p u b l i c c l a s s FileVisitorSample { 12 13 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 @Override 18 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 } 23 24 @Override 25 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 } 30 31 @Override 32 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 } 43 15
  • 17. WatchServiceSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.IOException; 11 12 p u b l i c c l a s s WatchServiceSample { 13 14 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 } 41 16
  • 18. AsynchronousSample.java 1 p a c k a g e java7.nio2; 2 3 i m p o r t java.io.FileInputStream; 15 16 p u b l i c c l a s s AsynchronousSample { 17 18 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 } 26 27 s t a t i c CountDownLatch write(InputStream in) { 28 ReadableByteChannel rbc = Channels. newChannel (in); 29 ByteBuffer buf = ByteBuffer. allocate (0x1000); 30 31 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 } 49 50 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; 55 56 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 } 66 67 @Override 68 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. AsynchronousSample.java 80 } c a t c h (IOException e) { 81 e.printStackTrace(); 82 latch.countDown(); 83 } 84 } 85 86 @Override 87 p u b l i c v o i d failed(Throwable exc, ByteBuffer buf) { 88 exc.printStackTrace(); 89 } 90 } 91 } 92 18
  • 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 } 16 19
  • 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. 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; 10 11 p u b l i c String getGreeting() { 12 r e t u r n myService.getGreeting(); 13 } 14 } 15 21
  • 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 } 11 22
  • 26. Notes This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/. 25