From f5a2dd0e00bd6c17e03b986cab68e8a806cd4305 Mon Sep 17 00:00:00 2001 From: Bruce Eckel Date: Tue, 5 May 2015 14:05:39 -0700 Subject: [PATCH] More Netbeans mods --- access/build.xml | 2 - annotations/InterfaceExtractorProcessor.java | 39 +++++---- annotations/build.xml | 2 - arrays/CompType.java | 7 +- arrays/CopyingArrays.java | 4 +- arrays/build.xml | 2 - assertions/build.xml | 2 - concurrency/ActiveObjectDemo.java | 22 ++--- concurrency/CloseResource.java | 20 ++--- concurrency/HorseRace.java | 35 ++++---- concurrency/NIOInterruption.java | 20 ++--- concurrency/SemaphoreDemo.java | 17 ++-- concurrency/build.xml | 2 - containers/build.xml | 2 - control/build.xml | 2 - debugging/build.xml | 2 - enumerated/EnumMaps.java | 10 +-- enumerated/build.xml | 2 - exceptions/build.xml | 2 - generics/BankTeller.java | 10 +-- generics/FactoryConstraint.java | 2 +- generics/build.xml | 2 - gui/Button2b.java | 9 +- gui/CheckBoxes.java | 21 ++--- gui/ComboBoxes.java | 18 ++-- gui/Dialogs.java | 14 +-- gui/Faces.java | 38 ++++----- gui/HTMLButton.java | 13 ++- gui/InterruptableLongRunningCallable.java | 36 +++----- gui/InterruptableLongRunningTask.java | 18 ++-- gui/List.java | 32 +++---- gui/LongRunningTask.java | 26 +++--- gui/MessageBoxes.java | 6 +- gui/MonitoredLongRunningCallable.java | 47 ++++------- gui/Popup.java | 7 +- gui/Progress.java | 7 +- gui/RadioButtons.java | 9 +- gui/SimpleMenus.java | 7 +- gui/SubmitLabelManipulationTask.java | 7 +- gui/SubmitSwingProgram.java | 12 +-- gui/TabbedPane1.java | 9 +- gui/TextArea.java | 16 ++-- gui/TextPane.java | 9 +- gui/build.xml | 2 - holding/AdapterMethodIdiom.java | 21 ++--- holding/ApplesAndOrangesWithGenerics.java | 5 +- holding/ApplesAndOrangesWithoutGenerics.java | 5 +- holding/MultiIterableClass.java | 34 +++----- holding/build.xml | 2 - initialization/ArrayInit.java | 6 +- initialization/AutoboxingVarargs.java | 4 +- initialization/NewVarArgs.java | 3 +- initialization/VarArgs.java | 3 +- initialization/build.xml | 2 - innerclasses/build.xml | 2 - interfaces/build.xml | 2 - io/BasicFileOutput.java | 14 +-- io/Blip3.java | 10 +-- io/Blips.java | 12 +-- io/BufferedInputFile.java | 17 ++-- io/FileLocking.java | 16 ++-- io/FileOutputShortcut.java | 14 +-- io/GZIPcompress.java | 19 +++-- io/Logon.java | 8 +- io/MappedIO.java | 89 ++++++++++---------- io/Redirecting.java | 25 +++--- io/StoringAndRecoveringData.java | 16 ++-- io/UsingRandomAccessFile.java | 12 +-- io/Worm.java | 11 +-- io/ZipCompress.java | 29 +++---- io/build.xml | 2 - logging/build.xml | 2 - net/build.xml | 4 +- net/mindview/atunit/AtUnitRemover.java | 1 + net/mindview/util/BinaryFile.java | 7 +- net/mindview/util/ProcessFiles.java | 7 +- net/mindview/util/RandomGenerator.java | 2 +- net/mindview/util/SwingConsole.java | 13 ++- net/mindview/util/TextFile.java | 21 ++--- network/build.xml | 2 - object/build.xml | 2 - operators/EqualsMethod.java | 4 +- operators/Equivalence.java | 4 +- operators/build.xml | 2 - patterns/ShapeFactory2.java | 6 +- patterns/build.xml | 2 - patterns/doubledispatch/DDAluminum.java | 6 +- patterns/doubledispatch/DDCardboard.java | 6 +- patterns/doubledispatch/DDGlass.java | 6 +- patterns/doubledispatch/DDPaper.java | 6 +- patterns/doubledispatch/DoubleDispatch.java | 5 +- patterns/factory/ShapeFactory1.java | 5 +- patterns/trash/ParseTrash.java | 31 ++++--- patterns/trash/Trash.java | 13 ++- polymorphism/build.xml | 2 - references/CheckCloneable.java | 5 +- references/Compete.java | 5 +- references/build.xml | 2 - remote/build.xml | 2 - reusing/build.xml | 2 - strings/WhitherStringBuilder.java | 10 ++- strings/build.xml | 2 - swt/ShellsAreMainWindows.java | 6 +- swt/build.xml | 2 - typeinfo/ShowMethods.java | 4 +- typeinfo/build.xml | 2 - unittesting/build.xml | 2 - xml/build.xml | 2 - 108 files changed, 474 insertions(+), 685 deletions(-) diff --git a/access/build.xml b/access/build.xml index cfae737b..ecd57b0f 100644 --- a/access/build.xml +++ b/access/build.xml @@ -6,7 +6,6 @@ - @@ -18,7 +17,6 @@ - diff --git a/annotations/InterfaceExtractorProcessor.java b/annotations/InterfaceExtractorProcessor.java index 840ba3a5..9c1ab794 100644 --- a/annotations/InterfaceExtractorProcessor.java +++ b/annotations/InterfaceExtractorProcessor.java @@ -30,28 +30,27 @@ public class InterfaceExtractorProcessor interfaceMethods.add(m); if(interfaceMethods.size() > 0) { try { - PrintWriter writer = - env.getFiler().createSourceFile(annot.value()); - writer.println("package " + - typeDecl.getPackage().getQualifiedName() +";"); - writer.println("public interface " + - annot.value() + " {"); - for(MethodDeclaration m : interfaceMethods) { - writer.print(" public "); - writer.print(m.getReturnType() + " "); - writer.print(m.getSimpleName() + " ("); - int i = 0; - for(ParameterDeclaration parm : - m.getParameters()) { - writer.print(parm.getType() + " " + - parm.getSimpleName()); - if(++i < m.getParameters().size()) - writer.print(", "); + try (PrintWriter writer = env.getFiler().createSourceFile(annot.value())) { + writer.println("package " + + typeDecl.getPackage().getQualifiedName() +";"); + writer.println("public interface " + + annot.value() + " {"); + for(MethodDeclaration m : interfaceMethods) { + writer.print(" public "); + writer.print(m.getReturnType() + " "); + writer.print(m.getSimpleName() + " ("); + int i = 0; + for(ParameterDeclaration parm : + m.getParameters()) { + writer.print(parm.getType() + " " + + parm.getSimpleName()); + if(++i < m.getParameters().size()) + writer.print(", "); + } + writer.println(");"); } - writer.println(");"); + writer.println("}"); } - writer.println("}"); - writer.close(); } catch(IOException ioe) { throw new RuntimeException(ioe); } diff --git a/annotations/build.xml b/annotations/build.xml index f83f83e4..4cfd0d52 100644 --- a/annotations/build.xml +++ b/annotations/build.xml @@ -6,7 +6,6 @@ - @@ -19,7 +18,6 @@ - diff --git a/arrays/CompType.java b/arrays/CompType.java index aa19da10..127dac8a 100644 --- a/arrays/CompType.java +++ b/arrays/CompType.java @@ -25,12 +25,7 @@ public class CompType implements Comparable { } private static Random r = new Random(47); public static Generator generator() { - return new Generator() { - @Override - public CompType next() { - return new CompType(r.nextInt(100),r.nextInt(100)); - } - }; + return () -> new CompType(r.nextInt(100),r.nextInt(100)); } public static void main(String[] args) { CompType[] a = diff --git a/arrays/CopyingArrays.java b/arrays/CopyingArrays.java index 3feaa2f5..a88c6472 100644 --- a/arrays/CopyingArrays.java +++ b/arrays/CopyingArrays.java @@ -23,8 +23,8 @@ public class CopyingArrays { // Objects: Integer[] u = new Integer[10]; Integer[] v = new Integer[5]; - Arrays.fill(u, new Integer(47)); - Arrays.fill(v, new Integer(99)); + Arrays.fill(u, 47); + Arrays.fill(v, 99); print("u = " + Arrays.toString(u)); print("v = " + Arrays.toString(v)); System.arraycopy(v, 0, u, u.length/2, v.length); diff --git a/arrays/build.xml b/arrays/build.xml index 605f4ea7..7ec162d6 100644 --- a/arrays/build.xml +++ b/arrays/build.xml @@ -6,7 +6,6 @@ - @@ -33,7 +32,6 @@ - diff --git a/assertions/build.xml b/assertions/build.xml index 5c65b0b4..0719f0e6 100644 --- a/assertions/build.xml +++ b/assertions/build.xml @@ -6,12 +6,10 @@ - - diff --git a/concurrency/ActiveObjectDemo.java b/concurrency/ActiveObjectDemo.java index aa274a3d..cc52e0e5 100644 --- a/concurrency/ActiveObjectDemo.java +++ b/concurrency/ActiveObjectDemo.java @@ -22,24 +22,18 @@ public class ActiveObjectDemo { } public Future calculateInt(final int x, final int y) { - return ex.submit(new Callable() { - @Override - public Integer call() { - print("starting " + x + " + " + y); - pause(500); - return x + y; - } + return ex.submit(() -> { + print("starting " + x + " + " + y); + pause(500); + return x + y; }); } public Future calculateFloat(final float x, final float y) { - return ex.submit(new Callable() { - @Override - public Float call() { - print("starting " + x + " + " + y); - pause(2000); - return x + y; - } + return ex.submit(() -> { + print("starting " + x + " + " + y); + pause(2000); + return x + y; }); } public void shutdown() { ex.shutdown(); } diff --git a/concurrency/CloseResource.java b/concurrency/CloseResource.java index aa8ad31a..2cff7dac 100644 --- a/concurrency/CloseResource.java +++ b/concurrency/CloseResource.java @@ -11,16 +11,16 @@ public class CloseResource { public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); ServerSocket server = new ServerSocket(8080); - InputStream socketInput = - new Socket("localhost", 8080).getInputStream(); - exec.execute(new IOBlocked(socketInput)); - exec.execute(new IOBlocked(System.in)); - TimeUnit.MILLISECONDS.sleep(100); - print("Shutting down all threads"); - exec.shutdownNow(); - TimeUnit.SECONDS.sleep(1); - print("Closing " + socketInput.getClass().getName()); - socketInput.close(); // Releases blocked thread + try (InputStream socketInput = new Socket("localhost", 8080).getInputStream()) { + exec.execute(new IOBlocked(socketInput)); + exec.execute(new IOBlocked(System.in)); + TimeUnit.MILLISECONDS.sleep(100); + print("Shutting down all threads"); + exec.shutdownNow(); + TimeUnit.SECONDS.sleep(1); + print("Closing " + socketInput.getClass().getName()); + socketInput.close(); // Releases blocked thread + } TimeUnit.SECONDS.sleep(1); print("Closing " + System.in.getClass().getName()); System.in.close(); // Releases blocked thread diff --git a/concurrency/HorseRace.java b/concurrency/HorseRace.java index d23f5a99..0a090d05 100644 --- a/concurrency/HorseRace.java +++ b/concurrency/HorseRace.java @@ -46,26 +46,23 @@ public class HorseRace { Executors.newCachedThreadPool(); private CyclicBarrier barrier; public HorseRace(int nHorses, final int pause) { - barrier = new CyclicBarrier(nHorses, new Runnable() { - @Override - public void run() { - StringBuilder s = new StringBuilder(); - for(int i = 0; i < FINISH_LINE; i++) - s.append("="); // The fence on the racetrack - print(s); - for(Horse horse : horses) - print(horse.tracks()); - for(Horse horse : horses) - if(horse.getStrides() >= FINISH_LINE) { - print(horse + "won!"); - exec.shutdownNow(); - return; - } - try { - TimeUnit.MILLISECONDS.sleep(pause); - } catch(InterruptedException e) { - print("barrier-action sleep interrupted"); + barrier = new CyclicBarrier(nHorses, () -> { + StringBuilder s = new StringBuilder(); + for(int i = 0; i < FINISH_LINE; i++) + s.append("="); // The fence on the racetrack + print(s); + for(Horse horse : horses) + print(horse.tracks()); + for(Horse horse : horses) + if(horse.getStrides() >= FINISH_LINE) { + print(horse + "won!"); + exec.shutdownNow(); + return; } + try { + TimeUnit.MILLISECONDS.sleep(pause); + } catch(InterruptedException e) { + print("barrier-action sleep interrupted"); } }); for(int i = 0; i < nHorses; i++) { diff --git a/concurrency/NIOInterruption.java b/concurrency/NIOInterruption.java index 719d1024..7e30c5da 100644 --- a/concurrency/NIOInterruption.java +++ b/concurrency/NIOInterruption.java @@ -33,16 +33,16 @@ public class NIOInterruption { InetSocketAddress isa = new InetSocketAddress("localhost", 8080); SocketChannel sc1 = SocketChannel.open(isa); - SocketChannel sc2 = SocketChannel.open(isa); - Future f = exec.submit(new NIOBlocked(sc1)); - exec.execute(new NIOBlocked(sc2)); - exec.shutdown(); - TimeUnit.SECONDS.sleep(1); - // Produce an interrupt via cancel: - f.cancel(true); - TimeUnit.SECONDS.sleep(1); - // Release the block by closing the channel: - sc2.close(); + try (SocketChannel sc2 = SocketChannel.open(isa)) { + Future f = exec.submit(new NIOBlocked(sc1)); + exec.execute(new NIOBlocked(sc2)); + exec.shutdown(); + TimeUnit.SECONDS.sleep(1); + // Produce an interrupt via cancel: + f.cancel(true); + TimeUnit.SECONDS.sleep(1); + // Release the block by closing the channel: + } } } /* Output: (Sample) Waiting for read() in NIOBlocked@7a84e4 diff --git a/concurrency/SemaphoreDemo.java b/concurrency/SemaphoreDemo.java index cccbe886..26613a8a 100644 --- a/concurrency/SemaphoreDemo.java +++ b/concurrency/SemaphoreDemo.java @@ -45,16 +45,13 @@ public class SemaphoreDemo { f.operation(); list.add(f); } - Future blocked = exec.submit(new Runnable() { - @Override - public void run() { - try { - // Semaphore prevents additional checkout, - // so call is blocked: - pool.checkOut(); - } catch(InterruptedException e) { - print("checkOut() Interrupted"); - } + Future blocked = exec.submit(() -> { + try { + // Semaphore prevents additional checkout, + // so call is blocked: + pool.checkOut(); + } catch(InterruptedException e) { + print("checkOut() Interrupted"); } }); TimeUnit.SECONDS.sleep(2); diff --git a/concurrency/build.xml b/concurrency/build.xml index eab4523a..67f20c93 100644 --- a/concurrency/build.xml +++ b/concurrency/build.xml @@ -6,7 +6,6 @@ - @@ -74,7 +73,6 @@ - diff --git a/containers/build.xml b/containers/build.xml index 95d5bb5f..cdb99b26 100644 --- a/containers/build.xml +++ b/containers/build.xml @@ -6,7 +6,6 @@ - @@ -44,7 +43,6 @@ - diff --git a/control/build.xml b/control/build.xml index 02e54739..ce9084df 100644 --- a/control/build.xml +++ b/control/build.xml @@ -6,7 +6,6 @@ - @@ -20,7 +19,6 @@ - diff --git a/debugging/build.xml b/debugging/build.xml index 6b201903..019b4dee 100644 --- a/debugging/build.xml +++ b/debugging/build.xml @@ -6,9 +6,7 @@ - - diff --git a/enumerated/EnumMaps.java b/enumerated/EnumMaps.java index 5b49a4b3..367ca93b 100644 --- a/enumerated/EnumMaps.java +++ b/enumerated/EnumMaps.java @@ -11,13 +11,11 @@ public class EnumMaps { public static void main(String[] args) { EnumMap em = new EnumMap<>(AlarmPoints.class); - em.put(KITCHEN, new Command() { - @Override - public void action() { print("Kitchen fire!"); } + em.put(KITCHEN, (Command) () -> { + print("Kitchen fire!"); }); - em.put(BATHROOM, new Command() { - @Override - public void action() { print("Bathroom alert!"); } + em.put(BATHROOM, (Command) () -> { + print("Bathroom alert!"); }); for(Map.Entry e : em.entrySet()) { printnb(e.getKey() + ": "); diff --git a/enumerated/build.xml b/enumerated/build.xml index 33d164a4..9c18961c 100644 --- a/enumerated/build.xml +++ b/enumerated/build.xml @@ -6,7 +6,6 @@ - @@ -34,7 +33,6 @@ - diff --git a/exceptions/build.xml b/exceptions/build.xml index ffc8ee99..39a54c5b 100644 --- a/exceptions/build.xml +++ b/exceptions/build.xml @@ -6,7 +6,6 @@ - @@ -31,7 +30,6 @@ - diff --git a/generics/BankTeller.java b/generics/BankTeller.java index 6d121510..5f5abe34 100644 --- a/generics/BankTeller.java +++ b/generics/BankTeller.java @@ -11,10 +11,7 @@ class Customer { public String toString() { return "Customer " + id; } // A method to produce Generator objects: public static Generator generator() { - return new Generator() { - @Override - public Customer next() { return new Customer(); } - }; + return () -> new Customer(); } } @@ -26,10 +23,7 @@ class Teller { public String toString() { return "Teller " + id; } // A single Generator object: public static Generator generator = - new Generator() { - @Override - public Teller next() { return new Teller(); } - }; + () -> new Teller(); } public class BankTeller { diff --git a/generics/FactoryConstraint.java b/generics/FactoryConstraint.java index 4df43c6d..2dbc1a9c 100644 --- a/generics/FactoryConstraint.java +++ b/generics/FactoryConstraint.java @@ -15,7 +15,7 @@ class Foo2 { class IntegerFactory implements FactoryI { @Override public Integer create() { - return new Integer(0); + return 0; } } diff --git a/generics/build.xml b/generics/build.xml index 28b9a737..8c0734bb 100644 --- a/generics/build.xml +++ b/generics/build.xml @@ -6,7 +6,6 @@ - @@ -78,7 +77,6 @@ - diff --git a/gui/Button2b.java b/gui/Button2b.java index 6f26390c..2fbe07df 100644 --- a/gui/Button2b.java +++ b/gui/Button2b.java @@ -10,12 +10,9 @@ public class Button2b extends JFrame { b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); - private ActionListener bl = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String name = ((JButton)e.getSource()).getText(); - txt.setText(name); - } + private ActionListener bl = (ActionEvent e) -> { + String name1 = ((JButton)e.getSource()).getText(); + txt.setText(name1); }; public Button2b() { b1.addActionListener(bl); diff --git a/gui/CheckBoxes.java b/gui/CheckBoxes.java index dc4b9637..b56d9518 100644 --- a/gui/CheckBoxes.java +++ b/gui/CheckBoxes.java @@ -12,23 +12,14 @@ public class CheckBoxes extends JFrame { cb2 = new JCheckBox("Check Box 2"), cb3 = new JCheckBox("Check Box 3"); public CheckBoxes() { - cb1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - trace("1", cb1); - } + cb1.addActionListener((ActionEvent e) -> { + trace("1", cb1); }); - cb2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - trace("2", cb2); - } + cb2.addActionListener((ActionEvent e) -> { + trace("2", cb2); }); - cb3.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - trace("3", cb3); - } + cb3.addActionListener((ActionEvent e) -> { + trace("3", cb3); }); setLayout(new FlowLayout()); add(new JScrollPane(t)); diff --git a/gui/ComboBoxes.java b/gui/ComboBoxes.java index 03c4db15..99f34d1b 100644 --- a/gui/ComboBoxes.java +++ b/gui/ComboBoxes.java @@ -18,19 +18,13 @@ public class ComboBoxes extends JFrame { for(int i = 0; i < 4; i++) c.addItem(description[count++]); t.setEditable(false); - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if(count < description.length) - c.addItem(description[count++]); - } + b.addActionListener((ActionEvent e) -> { + if(count < description.length) + c.addItem(description[count++]); }); - c.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - t.setText("index: "+ c.getSelectedIndex() + " " + - ((JComboBox)e.getSource()).getSelectedItem()); - } + c.addActionListener((ActionEvent e) -> { + t.setText("index: "+ c.getSelectedIndex() + " " + + ((JComboBox)e.getSource()).getSelectedItem()); }); setLayout(new FlowLayout()); add(t); diff --git a/gui/Dialogs.java b/gui/Dialogs.java index cab96fed..361e0aa8 100644 --- a/gui/Dialogs.java +++ b/gui/Dialogs.java @@ -11,11 +11,8 @@ class MyDialog extends JDialog { setLayout(new FlowLayout()); add(new JLabel("Here is my dialog")); JButton ok = new JButton("OK"); - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dispose(); // Closes the dialog - } + ok.addActionListener((ActionEvent e) -> { + dispose(); // Closes the dialog }); add(ok); setSize(150,125); @@ -26,11 +23,8 @@ public class Dialogs extends JFrame { private JButton b1 = new JButton("Dialog Box"); private MyDialog dlg = new MyDialog(null); public Dialogs() { - b1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dlg.setVisible(true); - } + b1.addActionListener((ActionEvent e) -> { + dlg.setVisible(true); }); add(b1); } diff --git a/gui/Faces.java b/gui/Faces.java index 6cb65f24..e558d9ff 100644 --- a/gui/Faces.java +++ b/gui/Faces.java @@ -19,19 +19,16 @@ public class Faces extends JFrame { }; jb = new JButton("JButton", faces[3]); setLayout(new FlowLayout()); - jb.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if(mad) { - jb.setIcon(faces[3]); - mad = false; - } else { - jb.setIcon(faces[0]); - mad = true; - } - jb.setVerticalAlignment(JButton.TOP); - jb.setHorizontalAlignment(JButton.LEFT); + jb.addActionListener((ActionEvent e) -> { + if(mad) { + jb.setIcon(faces[3]); + mad = false; + } else { + jb.setIcon(faces[0]); + mad = true; } + jb.setVerticalAlignment(JButton.TOP); + jb.setHorizontalAlignment(JButton.LEFT); }); jb.setRolloverEnabled(true); jb.setRolloverIcon(faces[1]); @@ -39,16 +36,13 @@ public class Faces extends JFrame { jb.setDisabledIcon(faces[4]); jb.setToolTipText("Yow!"); add(jb); - jb2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if(jb.isEnabled()) { - jb.setEnabled(false); - jb2.setText("Enable"); - } else { - jb.setEnabled(true); - jb2.setText("Disable"); - } + jb2.addActionListener((ActionEvent e) -> { + if(jb.isEnabled()) { + jb.setEnabled(false); + jb2.setText("Enable"); + } else { + jb.setEnabled(true); + jb2.setText("Disable"); } }); add(jb2); diff --git a/gui/HTMLButton.java b/gui/HTMLButton.java index 2ea7c1b4..f9b4fb47 100644 --- a/gui/HTMLButton.java +++ b/gui/HTMLButton.java @@ -10,14 +10,11 @@ public class HTMLButton extends JFrame { "" + "
Hello!
Press me now!"); public HTMLButton() { - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - add(new JLabel("" + - "Kapow!")); - // Force a re-layout to include the new label: - validate(); - } + b.addActionListener((ActionEvent e) -> { + add(new JLabel("" + + "Kapow!")); + // Force a re-layout to include the new label: + validate(); }); setLayout(new FlowLayout()); add(b); diff --git a/gui/InterruptableLongRunningCallable.java b/gui/InterruptableLongRunningCallable.java index 3d5f5d74..b0ece653 100644 --- a/gui/InterruptableLongRunningCallable.java +++ b/gui/InterruptableLongRunningCallable.java @@ -25,31 +25,21 @@ InterruptableLongRunningCallable extends JFrame { private TaskManager manager = new TaskManager<>(); public InterruptableLongRunningCallable() { - b1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - CallableTask task = new CallableTask(); - manager.add(task); - System.out.println(task + " added to the queue"); - } + b1.addActionListener((ActionEvent e) -> { + CallableTask task = new CallableTask(); + manager.add(task); + System.out.println(task + " added to the queue"); }); - b2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for(String result : manager.purge()) - System.out.println(result); - } + b2.addActionListener((ActionEvent e) -> { + for(String result : manager.purge()) + System.out.println(result); }); - b3.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Sample call to a Task method: - for(TaskItem tt : - manager) - tt.task.id(); // No cast required - for(String result : manager.getResults()) - System.out.println(result); - } + b3.addActionListener((ActionEvent e) -> { + // Sample call to a Task method: + for(TaskItem tt : manager) + tt.task.id(); // No cast required + for(String result : manager.getResults()) + System.out.println(result); }); setLayout(new FlowLayout()); add(b1); diff --git a/gui/InterruptableLongRunningTask.java b/gui/InterruptableLongRunningTask.java index f8d13871..8e03218e 100644 --- a/gui/InterruptableLongRunningTask.java +++ b/gui/InterruptableLongRunningTask.java @@ -32,19 +32,13 @@ public class InterruptableLongRunningTask extends JFrame { ExecutorService executor = Executors.newSingleThreadExecutor(); public InterruptableLongRunningTask() { - b1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Task task = new Task(); - executor.execute(task); - System.out.println(task + " added to the queue"); - } + b1.addActionListener((ActionEvent e) -> { + Task task = new Task(); + executor.execute(task); + System.out.println(task + " added to the queue"); }); - b2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - executor.shutdownNow(); // Heavy-handed - } + b2.addActionListener((ActionEvent e) -> { + executor.shutdownNow(); // Heavy-handed }); setLayout(new FlowLayout()); add(b1); diff --git a/gui/List.java b/gui/List.java index 2c16a3e3..a789411d 100644 --- a/gui/List.java +++ b/gui/List.java @@ -18,28 +18,22 @@ public class List extends JFrame { private JTextArea t = new JTextArea(flavors.length, 20); private JButton b = new JButton("Add Item"); - private ActionListener bl = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if(count < flavors.length) { - lItems.add(0, flavors[count++]); - } else { - // Disable, since there are no more - // flavors left to be added to the List - b.setEnabled(false); - } + private ActionListener bl = (ActionEvent e) -> { + if(count < flavors.length) { + lItems.add(0, flavors[count++]); + } else { + // Disable, since there are no more + // flavors left to be added to the List + b.setEnabled(false); } }; private ListSelectionListener ll = - new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - if(e.getValueIsAdjusting()) return; - t.setText(""); - for(Object item : lst.getSelectedValues()) - t.append(item + "\n"); - } - }; + (ListSelectionEvent e) -> { + if(e.getValueIsAdjusting()) return; + t.setText(""); + for(Object item : lst.getSelectedValues()) + t.append(item + "\n"); + }; public List() { t.setEditable(false); setLayout(new FlowLayout()); diff --git a/gui/LongRunningTask.java b/gui/LongRunningTask.java index 25e69297..c6766352 100644 --- a/gui/LongRunningTask.java +++ b/gui/LongRunningTask.java @@ -11,24 +11,18 @@ public class LongRunningTask extends JFrame { b1 = new JButton("Start Long Running Task"), b2 = new JButton("End Long Running Task"); public LongRunningTask() { - b1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent evt) { - try { - TimeUnit.SECONDS.sleep(3); - } catch(InterruptedException e) { - System.out.println("Task interrupted"); - return; - } - System.out.println("Task completed"); + b1.addActionListener((ActionEvent evt) -> { + try { + TimeUnit.SECONDS.sleep(3); + } catch(InterruptedException e) { + System.out.println("Task interrupted"); + return; } + System.out.println("Task completed"); }); - b2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent evt) { - // Interrupt yourself? - Thread.currentThread().interrupt(); - } + b2.addActionListener((ActionEvent evt) -> { + // Interrupt yourself? + Thread.currentThread().interrupt(); }); setLayout(new FlowLayout()); add(b1); diff --git a/gui/MessageBoxes.java b/gui/MessageBoxes.java index 8b64108b..0e378b0f 100644 --- a/gui/MessageBoxes.java +++ b/gui/MessageBoxes.java @@ -55,9 +55,9 @@ public class MessageBoxes extends JFrame { }; public MessageBoxes() { setLayout(new FlowLayout()); - for(int i = 0; i < b.length; i++) { - b[i].addActionListener(al); - add(b[i]); + for (JButton b1 : b) { + b1.addActionListener(al); + add(b1); } add(txt); } diff --git a/gui/MonitoredLongRunningCallable.java b/gui/MonitoredLongRunningCallable.java index 51679ab6..d31f7560 100644 --- a/gui/MonitoredLongRunningCallable.java +++ b/gui/MonitoredLongRunningCallable.java @@ -27,13 +27,9 @@ class MonitoredCallable implements Callable { if(monitor.isCanceled()) Thread.currentThread().interrupt(); final int progress = i; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - monitor.setProgress(progress); - } - } - ); + SwingUtilities.invokeLater(() -> { + monitor.setProgress(progress); + }); } } catch(InterruptedException e) { monitor.close(); @@ -55,31 +51,22 @@ public class MonitoredLongRunningCallable extends JFrame { private TaskManager manager = new TaskManager<>(); public MonitoredLongRunningCallable() { - b1.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MonitoredCallable task = new MonitoredCallable( - new ProgressMonitor( - MonitoredLongRunningCallable.this, - "Long-Running Task", "", 0, 0) - ); - manager.add(task); - System.out.println(task + " added to the queue"); - } + b1.addActionListener((ActionEvent e) -> { + MonitoredCallable task = new MonitoredCallable( + new ProgressMonitor( + MonitoredLongRunningCallable.this, + "Long-Running Task", "", 0, 0) + ); + manager.add(task); + System.out.println(task + " added to the queue"); }); - b2.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for(String result : manager.purge()) - System.out.println(result); - } + b2.addActionListener((ActionEvent e) -> { + for(String result : manager.purge()) + System.out.println(result); }); - b3.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for(String result : manager.getResults()) - System.out.println(result); - } + b3.addActionListener((ActionEvent e) -> { + for(String result : manager.getResults()) + System.out.println(result); }); setLayout(new FlowLayout()); add(b1); diff --git a/gui/Popup.java b/gui/Popup.java index b5009582..0ab455be 100644 --- a/gui/Popup.java +++ b/gui/Popup.java @@ -11,11 +11,8 @@ public class Popup extends JFrame { public Popup() { setLayout(new FlowLayout()); add(t); - ActionListener al = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - t.setText(((JMenuItem)e.getSource()).getText()); - } + ActionListener al = (ActionEvent e) -> { + t.setText(((JMenuItem)e.getSource()).getText()); }; JMenuItem m = new JMenuItem("Hither"); m.addActionListener(al); diff --git a/gui/Progress.java b/gui/Progress.java index f96bf988..9b717842 100644 --- a/gui/Progress.java +++ b/gui/Progress.java @@ -24,11 +24,8 @@ public class Progress extends JFrame { sb.setBorder(new TitledBorder("Slide Me")); pb.setModel(sb.getModel()); // Share model add(sb); - sb.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - pm.setProgress(sb.getValue()); - } + sb.addChangeListener((ChangeEvent e) -> { + pm.setProgress(sb.getValue()); }); } public static void main(String[] args) { diff --git a/gui/RadioButtons.java b/gui/RadioButtons.java index d1a79c1a..90798932 100644 --- a/gui/RadioButtons.java +++ b/gui/RadioButtons.java @@ -12,12 +12,9 @@ public class RadioButtons extends JFrame { rb1 = new JRadioButton("one", false), rb2 = new JRadioButton("two", false), rb3 = new JRadioButton("three", false); - private ActionListener al = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - t.setText("Radio button " + - ((JRadioButton)e.getSource()).getText()); - } + private ActionListener al = (ActionEvent e) -> { + t.setText("Radio button " + + ((JRadioButton)e.getSource()).getText()); }; public RadioButtons() { rb1.addActionListener(al); diff --git a/gui/SimpleMenus.java b/gui/SimpleMenus.java index 1b99beb5..a779f4e2 100644 --- a/gui/SimpleMenus.java +++ b/gui/SimpleMenus.java @@ -6,11 +6,8 @@ import static net.mindview.util.SwingConsole.*; public class SimpleMenus extends JFrame { private JTextField t = new JTextField(15); - private ActionListener al = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - t.setText(((JMenuItem)e.getSource()).getText()); - } + private ActionListener al = (ActionEvent e) -> { + t.setText(((JMenuItem)e.getSource()).getText()); }; private JMenu[] menus = { new JMenu("Winken"), new JMenu("Blinken"), diff --git a/gui/SubmitLabelManipulationTask.java b/gui/SubmitLabelManipulationTask.java index 483878f7..db76bde4 100644 --- a/gui/SubmitLabelManipulationTask.java +++ b/gui/SubmitLabelManipulationTask.java @@ -11,11 +11,8 @@ public class SubmitLabelManipulationTask { frame.setSize(300, 100); frame.setVisible(true); TimeUnit.SECONDS.sleep(1); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - label.setText("Hey! This is Different!"); - } + SwingUtilities.invokeLater(() -> { + label.setText("Hey! This is Different!"); }); } } ///:~ diff --git a/gui/SubmitSwingProgram.java b/gui/SubmitSwingProgram.java index a02f6364..85f71459 100644 --- a/gui/SubmitSwingProgram.java +++ b/gui/SubmitSwingProgram.java @@ -14,16 +14,12 @@ public class SubmitSwingProgram extends JFrame { } static SubmitSwingProgram ssp; public static void main(String[] args) throws Exception { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { ssp = new SubmitSwingProgram(); } + SwingUtilities.invokeLater(() -> { + ssp = new SubmitSwingProgram(); }); TimeUnit.SECONDS.sleep(1); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ssp.label.setText("Hey! This is Different!"); - } + SwingUtilities.invokeLater(() -> { + ssp.label.setText("Hey! This is Different!"); }); } } ///:~ diff --git a/gui/TabbedPane1.java b/gui/TabbedPane1.java index 2302dc81..6000c0e8 100644 --- a/gui/TabbedPane1.java +++ b/gui/TabbedPane1.java @@ -18,12 +18,9 @@ public class TabbedPane1 extends JFrame { for(String flavor : flavors) tabs.addTab(flavors[i], new JButton("Tabbed pane " + i++)); - tabs.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - txt.setText("Tab selected: " + - tabs.getSelectedIndex()); - } + tabs.addChangeListener((ChangeEvent e) -> { + txt.setText("Tab selected: " + + tabs.getSelectedIndex()); }); add(BorderLayout.SOUTH, txt); add(tabs); diff --git a/gui/TextArea.java b/gui/TextArea.java index bc5b465c..c2bb3142 100644 --- a/gui/TextArea.java +++ b/gui/TextArea.java @@ -16,18 +16,12 @@ public class TextArea extends JFrame { public TextArea() { // Use up all the data: m.putAll(Countries.capitals()); - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for(Map.Entry me : m.entrySet()) - t.append(me.getKey() + ": "+ me.getValue()+"\n"); - } + b.addActionListener((ActionEvent e) -> { + for(Map.Entry me : m.entrySet()) + t.append(me.getKey() + ": "+ me.getValue()+"\n"); }); - c.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - t.setText(""); - } + c.addActionListener((ActionEvent e) -> { + t.setText(""); }); setLayout(new FlowLayout()); add(new JScrollPane(t)); diff --git a/gui/TextPane.java b/gui/TextPane.java index f6c858a5..639106c5 100644 --- a/gui/TextPane.java +++ b/gui/TextPane.java @@ -12,12 +12,9 @@ public class TextPane extends JFrame { private static Generator sg = new RandomGenerator.String(7); public TextPane() { - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for(int i = 1; i < 10; i++) - tp.setText(tp.getText() + sg.next() + "\n"); - } + b.addActionListener((ActionEvent e) -> { + for(int i = 1; i < 10; i++) + tp.setText(tp.getText() + sg.next() + "\n"); }); add(new JScrollPane(tp)); add(BorderLayout.SOUTH, b); diff --git a/gui/build.xml b/gui/build.xml index 02cc5678..b30d1a39 100644 --- a/gui/build.xml +++ b/gui/build.xml @@ -6,7 +6,6 @@ - @@ -47,7 +46,6 @@ - diff --git a/holding/AdapterMethodIdiom.java b/holding/AdapterMethodIdiom.java index e7fc366c..ee572332 100644 --- a/holding/AdapterMethodIdiom.java +++ b/holding/AdapterMethodIdiom.java @@ -6,20 +6,15 @@ import java.util.*; class ReversibleArrayList extends ArrayList { public ReversibleArrayList(Collection c) { super(c); } public Iterable reversed() { - return new Iterable() { + return () -> new Iterator() { + int current = size() - 1; @Override - public Iterator iterator() { - return new Iterator() { - int current = size() - 1; - @Override - public boolean hasNext() { return current > -1; } - @Override - public T next() { return get(current--); } - @Override - public void remove() { // Not implemented - throw new UnsupportedOperationException(); - } - }; + public boolean hasNext() { return current > -1; } + @Override + public T next() { return get(current--); } + @Override + public void remove() { // Not implemented + throw new UnsupportedOperationException(); } }; } diff --git a/holding/ApplesAndOrangesWithGenerics.java b/holding/ApplesAndOrangesWithGenerics.java index 76ab486e..3c49bf0a 100644 --- a/holding/ApplesAndOrangesWithGenerics.java +++ b/holding/ApplesAndOrangesWithGenerics.java @@ -8,8 +8,9 @@ public class ApplesAndOrangesWithGenerics { apples.add(new Apple()); // Compile-time error: // apples.add(new Orange()); - for(int i = 0; i < apples.size(); i++) - System.out.println(apples.get(i).id()); + for (Apple apple : apples) { + System.out.println(apple.id()); + } // Using foreach: for(Apple c : apples) System.out.println(c.id()); diff --git a/holding/ApplesAndOrangesWithoutGenerics.java b/holding/ApplesAndOrangesWithoutGenerics.java index 40a57f00..502a7298 100644 --- a/holding/ApplesAndOrangesWithoutGenerics.java +++ b/holding/ApplesAndOrangesWithoutGenerics.java @@ -19,8 +19,9 @@ public class ApplesAndOrangesWithoutGenerics { apples.add(new Apple()); // Not prevented from adding an Orange to apples: apples.add(new Orange()); - for(int i = 0; i < apples.size(); i++) - ((Apple)apples.get(i)).id(); + for (Object apple : apples) { + ((Apple) apple).id(); // Orange is detected only at run time + } } } /* (Execute to see output) *///:~ diff --git a/holding/MultiIterableClass.java b/holding/MultiIterableClass.java index 8fe56c21..3fedb240 100644 --- a/holding/MultiIterableClass.java +++ b/holding/MultiIterableClass.java @@ -4,32 +4,24 @@ import java.util.*; public class MultiIterableClass extends IterableClass { public Iterable reversed() { - return new Iterable() { + return () -> new Iterator() { + int current = words.length - 1; @Override - public Iterator iterator() { - return new Iterator() { - int current = words.length - 1; - @Override - public boolean hasNext() { return current > -1; } - @Override - public String next() { return words[current--]; } - @Override - public void remove() { // Not implemented - throw new UnsupportedOperationException(); - } - }; + public boolean hasNext() { return current > -1; } + @Override + public String next() { return words[current--]; } + @Override + public void remove() { // Not implemented + throw new UnsupportedOperationException(); } }; } public Iterable randomized() { - return new Iterable() { - @Override - public Iterator iterator() { - List shuffled = - new ArrayList<>(Arrays.asList(words)); - Collections.shuffle(shuffled, new Random(47)); - return shuffled.iterator(); - } + return () -> { + List shuffled = + new ArrayList<>(Arrays.asList(words)); + Collections.shuffle(shuffled, new Random(47)); + return shuffled.iterator(); }; } public static void main(String[] args) { diff --git a/holding/build.xml b/holding/build.xml index f5727e4a..68994c9d 100644 --- a/holding/build.xml +++ b/holding/build.xml @@ -6,7 +6,6 @@ - @@ -42,7 +41,6 @@ - diff --git a/initialization/ArrayInit.java b/initialization/ArrayInit.java index bb944465..304643f0 100644 --- a/initialization/ArrayInit.java +++ b/initialization/ArrayInit.java @@ -5,13 +5,11 @@ import java.util.*; public class ArrayInit { public static void main(String[] args) { Integer[] a = { - new Integer(1), - new Integer(2), + 1, 2, 3, // Autoboxing }; Integer[] b = new Integer[]{ - new Integer(1), - new Integer(2), + 1, 2, 3, // Autoboxing }; System.out.println(Arrays.toString(a)); diff --git a/initialization/AutoboxingVarargs.java b/initialization/AutoboxingVarargs.java index 9e9284fe..6c955537 100644 --- a/initialization/AutoboxingVarargs.java +++ b/initialization/AutoboxingVarargs.java @@ -7,9 +7,9 @@ public class AutoboxingVarargs { System.out.println(); } public static void main(String[] args) { - f(new Integer(1), new Integer(2)); + f(1, 2); f(4, 5, 6, 7, 8, 9); - f(10, new Integer(11), 12); + f(10, 11, 12); } } /* Output: 1 2 diff --git a/initialization/NewVarArgs.java b/initialization/NewVarArgs.java index 776c0cdb..ec7c4d32 100644 --- a/initialization/NewVarArgs.java +++ b/initialization/NewVarArgs.java @@ -9,8 +9,7 @@ public class NewVarArgs { } public static void main(String[] args) { // Can take individual elements: - printArray(new Integer(47), new Float(3.14), - new Double(11.11)); + printArray(47, (float) 3.14, 11.11); printArray(47, 3.14F, 11.11); printArray("one", "two", "three"); printArray(new A(), new A(), new A()); diff --git a/initialization/VarArgs.java b/initialization/VarArgs.java index 3623196b..56b06dd8 100644 --- a/initialization/VarArgs.java +++ b/initialization/VarArgs.java @@ -11,8 +11,7 @@ public class VarArgs { } public static void main(String[] args) { printArray(new Object[]{ - new Integer(47), new Float(3.14), new Double(11.11) - }); + 47, (float) 3.14, 11.11}); printArray(new Object[]{"one", "two", "three" }); printArray(new Object[]{new A(), new A(), new A()}); } diff --git a/initialization/build.xml b/initialization/build.xml index ff9eff1a..a05dac0a 100644 --- a/initialization/build.xml +++ b/initialization/build.xml @@ -6,7 +6,6 @@ - @@ -40,7 +39,6 @@ - diff --git a/innerclasses/build.xml b/innerclasses/build.xml index 80c13c02..f16a599b 100644 --- a/innerclasses/build.xml +++ b/innerclasses/build.xml @@ -6,7 +6,6 @@ - @@ -36,7 +35,6 @@ - diff --git a/interfaces/build.xml b/interfaces/build.xml index 3fac2e35..a1d15ac3 100644 --- a/interfaces/build.xml +++ b/interfaces/build.xml @@ -6,7 +6,6 @@ - @@ -21,7 +20,6 @@ - diff --git a/io/BasicFileOutput.java b/io/BasicFileOutput.java index c4b546f7..e19920dc 100644 --- a/io/BasicFileOutput.java +++ b/io/BasicFileOutput.java @@ -8,13 +8,13 @@ public class BasicFileOutput { BufferedReader in = new BufferedReader( new StringReader( BufferedInputFile.read("BasicFileOutput.java"))); - PrintWriter out = new PrintWriter( - new BufferedWriter(new FileWriter(file))); - int lineCount = 1; - String s; - while((s = in.readLine()) != null ) - out.println(lineCount++ + ": " + s); - out.close(); + try (PrintWriter out = new PrintWriter( + new BufferedWriter(new FileWriter(file)))) { + int lineCount = 1; + String s; + while((s = in.readLine()) != null ) + out.println(lineCount++ + ": " + s); + } // Show the stored file: System.out.println(BufferedInputFile.read(file)); } diff --git a/io/Blip3.java b/io/Blip3.java index a84d4d04..a02197f1 100644 --- a/io/Blip3.java +++ b/io/Blip3.java @@ -39,11 +39,11 @@ public class Blip3 implements Externalizable { print("Constructing objects:"); Blip3 b3 = new Blip3("A String ", 47); print(b3); - ObjectOutputStream o = new ObjectOutputStream( - new FileOutputStream("Blip3.out")); - print("Saving object:"); - o.writeObject(b3); - o.close(); + try (ObjectOutputStream o = new ObjectOutputStream( + new FileOutputStream("Blip3.out"))) { + print("Saving object:"); + o.writeObject(b3); + } // Now get it back: ObjectInputStream in = new ObjectInputStream( new FileInputStream("Blip3.out")); diff --git a/io/Blips.java b/io/Blips.java index c83bcfcc..5c3f2694 100644 --- a/io/Blips.java +++ b/io/Blips.java @@ -41,12 +41,12 @@ public class Blips { print("Constructing objects:"); Blip1 b1 = new Blip1(); Blip2 b2 = new Blip2(); - ObjectOutputStream o = new ObjectOutputStream( - new FileOutputStream("Blips.out")); - print("Saving objects:"); - o.writeObject(b1); - o.writeObject(b2); - o.close(); + try (ObjectOutputStream o = new ObjectOutputStream( + new FileOutputStream("Blips.out"))) { + print("Saving objects:"); + o.writeObject(b1); + o.writeObject(b2); + } // Now get them back: ObjectInputStream in = new ObjectInputStream( new FileInputStream("Blips.out")); diff --git a/io/BufferedInputFile.java b/io/BufferedInputFile.java index e6df357f..00f0635b 100644 --- a/io/BufferedInputFile.java +++ b/io/BufferedInputFile.java @@ -5,14 +5,15 @@ public class BufferedInputFile { // Throw exceptions to console: public static String read(String filename) throws IOException { - // Reading input by lines: - BufferedReader in = new BufferedReader( - new FileReader(filename)); - String s; - StringBuilder sb = new StringBuilder(); - while((s = in.readLine())!= null) - sb.append(s + "\n"); - in.close(); + StringBuilder sb; + try ( // Reading input by lines: + BufferedReader in = new BufferedReader( + new FileReader(filename))) { + String s; + sb = new StringBuilder(); + while((s = in.readLine())!= null) + sb.append(s + "\n"); + } return sb.toString(); } public static void main(String[] args) diff --git a/io/FileLocking.java b/io/FileLocking.java index 17d95684..521839a2 100644 --- a/io/FileLocking.java +++ b/io/FileLocking.java @@ -5,15 +5,15 @@ import java.io.*; public class FileLocking { public static void main(String[] args) throws Exception { - FileOutputStream fos= new FileOutputStream("file.txt"); - FileLock fl = fos.getChannel().tryLock(); - if(fl != null) { - System.out.println("Locked File"); - TimeUnit.MILLISECONDS.sleep(100); - fl.release(); - System.out.println("Released Lock"); + try (FileOutputStream fos = new FileOutputStream("file.txt")) { + FileLock fl = fos.getChannel().tryLock(); + if(fl != null) { + System.out.println("Locked File"); + TimeUnit.MILLISECONDS.sleep(100); + fl.release(); + System.out.println("Released Lock"); + } } - fos.close(); } } /* Output: Locked File diff --git a/io/FileOutputShortcut.java b/io/FileOutputShortcut.java index 50ece447..6c50bf78 100644 --- a/io/FileOutputShortcut.java +++ b/io/FileOutputShortcut.java @@ -8,13 +8,13 @@ public class FileOutputShortcut { BufferedReader in = new BufferedReader( new StringReader( BufferedInputFile.read("FileOutputShortcut.java"))); - // Here's the shortcut: - PrintWriter out = new PrintWriter(file); - int lineCount = 1; - String s; - while((s = in.readLine()) != null ) - out.println(lineCount++ + ": " + s); - out.close(); + try ( // Here's the shortcut: + PrintWriter out = new PrintWriter(file)) { + int lineCount = 1; + String s; + while((s = in.readLine()) != null ) + out.println(lineCount++ + ": " + s); + } // Show the stored file: System.out.println(BufferedInputFile.read(file)); } diff --git a/io/GZIPcompress.java b/io/GZIPcompress.java index 70d8b956..19ba78f5 100644 --- a/io/GZIPcompress.java +++ b/io/GZIPcompress.java @@ -13,16 +13,17 @@ public class GZIPcompress { "the file to test.gz"); System.exit(1); } - InputStream in = new BufferedInputStream( - new FileInputStream(args[0])); - BufferedOutputStream out = new BufferedOutputStream( - new GZIPOutputStream( - new FileOutputStream("test.gz"))); - System.out.println("Writing file"); - int c; - while((c = in.read()) != -1) + BufferedOutputStream out; + try (InputStream in = new BufferedInputStream( + new FileInputStream(args[0]))) { + out = new BufferedOutputStream( + new GZIPOutputStream( + new FileOutputStream("test.gz"))); + System.out.println("Writing file"); + int c; + while((c = in.read()) != -1) out.write(c); - in.close(); + } out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader( diff --git a/io/Logon.java b/io/Logon.java index a1cd9768..f36eb44c 100644 --- a/io/Logon.java +++ b/io/Logon.java @@ -21,10 +21,10 @@ public class Logon implements Serializable { public static void main(String[] args) throws Exception { Logon a = new Logon("Hulk", "myLittlePony"); print("logon a = " + a); - ObjectOutputStream o = new ObjectOutputStream( - new FileOutputStream("Logon.out")); - o.writeObject(a); - o.close(); + try (ObjectOutputStream o = new ObjectOutputStream( + new FileOutputStream("Logon.out"))) { + o.writeObject(a); + } TimeUnit.SECONDS.sleep(1); // Delay // Now get them back: ObjectInputStream in = new ObjectInputStream( diff --git a/io/MappedIO.java b/io/MappedIO.java index 2e05a7c0..f72e96b7 100644 --- a/io/MappedIO.java +++ b/io/MappedIO.java @@ -26,77 +26,76 @@ public class MappedIO { new Tester("Stream Write") { @Override public void test() throws IOException { - DataOutputStream dos = new DataOutputStream( - new BufferedOutputStream( - new FileOutputStream(new File("temp.tmp")))); - for(int i = 0; i < numOfInts; i++) - dos.writeInt(i); - dos.close(); + try (DataOutputStream dos = new DataOutputStream( + new BufferedOutputStream( + new FileOutputStream(new File("temp.tmp"))))) { + for(int i = 0; i < numOfInts; i++) + dos.writeInt(i); + } } }, new Tester("Mapped Write") { @Override public void test() throws IOException { - FileChannel fc = - new RandomAccessFile("temp.tmp", "rw") - .getChannel(); - IntBuffer ib = fc.map( - FileChannel.MapMode.READ_WRITE, 0, fc.size()) - .asIntBuffer(); - for(int i = 0; i < numOfInts; i++) - ib.put(i); - fc.close(); + try (FileChannel fc = new RandomAccessFile("temp.tmp", "rw") + .getChannel()) { + IntBuffer ib = fc.map( + FileChannel.MapMode.READ_WRITE, 0, fc.size()) + .asIntBuffer(); + for(int i = 0; i < numOfInts; i++) + ib.put(i); + } } }, new Tester("Stream Read") { @Override public void test() throws IOException { - DataInputStream dis = new DataInputStream( - new BufferedInputStream( - new FileInputStream("temp.tmp"))); - for(int i = 0; i < numOfInts; i++) - dis.readInt(); - dis.close(); + try (DataInputStream dis = new DataInputStream( + new BufferedInputStream( + new FileInputStream("temp.tmp")))) { + for(int i = 0; i < numOfInts; i++) + dis.readInt(); + } } }, new Tester("Mapped Read") { @Override public void test() throws IOException { - FileChannel fc = new FileInputStream( - new File("temp.tmp")).getChannel(); - IntBuffer ib = fc.map( - FileChannel.MapMode.READ_ONLY, 0, fc.size()) - .asIntBuffer(); - while(ib.hasRemaining()) - ib.get(); - fc.close(); + try (FileChannel fc = new FileInputStream( + new File("temp.tmp")).getChannel()) { + IntBuffer ib = fc.map( + FileChannel.MapMode.READ_ONLY, 0, fc.size()) + .asIntBuffer(); + while(ib.hasRemaining()) + ib.get(); + } } }, new Tester("Stream Read/Write") { @Override public void test() throws IOException { - RandomAccessFile raf = new RandomAccessFile( - new File("temp.tmp"), "rw"); - raf.writeInt(1); - for(int i = 0; i < numOfUbuffInts; i++) { - raf.seek(raf.length() - 4); - raf.writeInt(raf.readInt()); + try (RandomAccessFile raf = new RandomAccessFile( + new File("temp.tmp"), "rw")) { + raf.writeInt(1); + for(int i = 0; i < numOfUbuffInts; i++) { + raf.seek(raf.length() - 4); + raf.writeInt(raf.readInt()); + } } - raf.close(); } }, new Tester("Mapped Read/Write") { @Override public void test() throws IOException { - FileChannel fc = new RandomAccessFile( - new File("temp.tmp"), "rw").getChannel(); - IntBuffer ib = fc.map( - FileChannel.MapMode.READ_WRITE, 0, fc.size()) - .asIntBuffer(); - ib.put(0); - for(int i = 1; i < numOfUbuffInts; i++) - ib.put(ib.get(i - 1)); - fc.close(); + try (FileChannel fc = new RandomAccessFile( + new File("temp.tmp"), "rw").getChannel()) { + IntBuffer ib = fc.map( + FileChannel.MapMode.READ_WRITE, 0, fc.size()) + .asIntBuffer(); + ib.put(0); + for(int i = 1; i < numOfUbuffInts; i++) + ib.put(ib.get(i - 1)); + } } } }; diff --git a/io/Redirecting.java b/io/Redirecting.java index da451b28..d4c9d0df 100644 --- a/io/Redirecting.java +++ b/io/Redirecting.java @@ -8,18 +8,19 @@ public class Redirecting { PrintStream console = System.out; BufferedInputStream in = new BufferedInputStream( new FileInputStream("Redirecting.java")); - PrintStream out = new PrintStream( - new BufferedOutputStream( - new FileOutputStream("test.out"))); - System.setIn(in); - System.setOut(out); - System.setErr(out); - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in)); - String s; - while((s = br.readLine()) != null) - System.out.println(s); - out.close(); // Remember this! + try (PrintStream out = new PrintStream( + new BufferedOutputStream( + new FileOutputStream("test.out")))) { + System.setIn(in); + System.setOut(out); + System.setErr(out); + BufferedReader br = new BufferedReader( + new InputStreamReader(System.in)); + String s; + while((s = br.readLine()) != null) + System.out.println(s); + out.close(); // Remember this! + } System.setOut(console); } } ///:~ diff --git a/io/StoringAndRecoveringData.java b/io/StoringAndRecoveringData.java index 0d6de39a..59f73201 100644 --- a/io/StoringAndRecoveringData.java +++ b/io/StoringAndRecoveringData.java @@ -4,14 +4,14 @@ import java.io.*; public class StoringAndRecoveringData { public static void main(String[] args) throws IOException { - DataOutputStream out = new DataOutputStream( - new BufferedOutputStream( - new FileOutputStream("Data.txt"))); - out.writeDouble(3.14159); - out.writeUTF("That was pi"); - out.writeDouble(1.41413); - out.writeUTF("Square root of 2"); - out.close(); + try (DataOutputStream out = new DataOutputStream( + new BufferedOutputStream( + new FileOutputStream("Data.txt")))) { + out.writeDouble(3.14159); + out.writeUTF("That was pi"); + out.writeDouble(1.41413); + out.writeUTF("Square root of 2"); + } DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("Data.txt"))); diff --git a/io/UsingRandomAccessFile.java b/io/UsingRandomAccessFile.java index 6327b64e..da72d1f7 100644 --- a/io/UsingRandomAccessFile.java +++ b/io/UsingRandomAccessFile.java @@ -4,12 +4,12 @@ import java.io.*; public class UsingRandomAccessFile { static String file = "rtest.dat"; static void display() throws IOException { - RandomAccessFile rf = new RandomAccessFile(file, "r"); - for(int i = 0; i < 7; i++) - System.out.println( - "Value " + i + ": " + rf.readDouble()); - System.out.println(rf.readUTF()); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "r")) { + for(int i = 0; i < 7; i++) + System.out.println( + "Value " + i + ": " + rf.readDouble()); + System.out.println(rf.readUTF()); + } } public static void main(String[] args) throws IOException { diff --git a/io/Worm.java b/io/Worm.java index 89dfa260..8f4341cc 100644 --- a/io/Worm.java +++ b/io/Worm.java @@ -46,11 +46,12 @@ public class Worm implements Serializable { throws ClassNotFoundException, IOException { Worm w = new Worm(6, 'a'); print("w = " + w); - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("worm.out")); - out.writeObject("Worm storage\n"); - out.writeObject(w); - out.close(); // Also flushes output + try (ObjectOutputStream out = new ObjectOutputStream( + new FileOutputStream("worm.out"))) { + out.writeObject("Worm storage\n"); + out.writeObject(w); + out.close(); // Also flushes output + } ObjectInputStream in = new ObjectInputStream( new FileInputStream("worm.out")); String s = (String)in.readObject(); diff --git a/io/ZipCompress.java b/io/ZipCompress.java index 3dd5d616..a8d15861 100644 --- a/io/ZipCompress.java +++ b/io/ZipCompress.java @@ -14,22 +14,21 @@ public class ZipCompress { CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); - BufferedOutputStream out = - new BufferedOutputStream(zos); - zos.setComment("A test of Java Zipping"); - // No corresponding getComment(), though. - for(String arg : args) { - print("Writing file " + arg); - InputStream in = new BufferedInputStream( - new FileInputStream(arg)); - zos.putNextEntry(new ZipEntry(arg)); - int c; - while((c = in.read()) != -1) - out.write(c); - in.close(); - out.flush(); + try (BufferedOutputStream out = new BufferedOutputStream(zos)) { + zos.setComment("A test of Java Zipping"); + // No corresponding getComment(), though. + for (String arg : args) { + print("Writing file " + arg); + try (InputStream in = new BufferedInputStream( + new FileInputStream(arg))) { + zos.putNextEntry(new ZipEntry(arg)); + int c; + while((c = in.read()) != -1) + out.write(c); + } + out.flush(); + } } - out.close(); // Checksum valid only after the file is closed! print("Checksum: " + csum.getChecksum().getValue()); // Now extract the files: diff --git a/io/build.xml b/io/build.xml index baa0481e..006e1298 100644 --- a/io/build.xml +++ b/io/build.xml @@ -6,7 +6,6 @@ - @@ -51,7 +50,6 @@ - diff --git a/logging/build.xml b/logging/build.xml index 6aedb7c3..69d6a2a2 100644 --- a/logging/build.xml +++ b/logging/build.xml @@ -6,7 +6,6 @@ - @@ -19,7 +18,6 @@ - diff --git a/net/build.xml b/net/build.xml index 5238217a..ca99e24c 100644 --- a/net/build.xml +++ b/net/build.xml @@ -6,9 +6,8 @@ - - + @@ -19,7 +18,6 @@ - diff --git a/net/mindview/atunit/AtUnitRemover.java b/net/mindview/atunit/AtUnitRemover.java index 187cf228..70e73c63 100644 --- a/net/mindview/atunit/AtUnitRemover.java +++ b/net/mindview/atunit/AtUnitRemover.java @@ -1,6 +1,7 @@ //: net/mindview/atunit/AtUnitRemover.java // Displays @Unit annotations in compiled class files. If // first argument is "-r", @Unit annotations are removed. +// {ThrowsException} Some kind of bug here... // {Args: ..} // {Requires: javassist.bytecode.ClassFile; // You must install the Javassist library from diff --git a/net/mindview/util/BinaryFile.java b/net/mindview/util/BinaryFile.java index fa8a6239..c0dae2e4 100644 --- a/net/mindview/util/BinaryFile.java +++ b/net/mindview/util/BinaryFile.java @@ -5,14 +5,11 @@ import java.io.*; public class BinaryFile { public static byte[] read(File bFile) throws IOException{ - BufferedInputStream bf = new BufferedInputStream( - new FileInputStream(bFile)); - try { + try (BufferedInputStream bf = new BufferedInputStream( + new FileInputStream(bFile))) { byte[] data = new byte[bf.available()]; bf.read(data); return data; - } finally { - bf.close(); } } public static byte[] diff --git a/net/mindview/util/ProcessFiles.java b/net/mindview/util/ProcessFiles.java index cdb710d5..dc7faa9e 100644 --- a/net/mindview/util/ProcessFiles.java +++ b/net/mindview/util/ProcessFiles.java @@ -41,11 +41,8 @@ public class ProcessFiles { } // Demonstration of how to use it: public static void main(String[] args) { - new ProcessFiles(new ProcessFiles.Strategy() { - @Override - public void process(File file) { - System.out.println(file); - } + new ProcessFiles((File file) -> { + System.out.println(file); }, "java").start(args); } } /* (Execute to see output) *///:~ diff --git a/net/mindview/util/RandomGenerator.java b/net/mindview/util/RandomGenerator.java index 4f1c62b1..9b9b25d2 100644 --- a/net/mindview/util/RandomGenerator.java +++ b/net/mindview/util/RandomGenerator.java @@ -58,7 +58,7 @@ public class RandomGenerator { public Long(int modulo) { mod = modulo; } @Override public java.lang.Long next() { - return new java.lang.Long(r.nextInt(mod)); + return (long) r.nextInt(mod); } } public static class diff --git a/net/mindview/util/SwingConsole.java b/net/mindview/util/SwingConsole.java index c1733e7e..85bec3b5 100644 --- a/net/mindview/util/SwingConsole.java +++ b/net/mindview/util/SwingConsole.java @@ -7,14 +7,11 @@ import javax.swing.*; public class SwingConsole { public static void run(final JFrame f, final int width, final int height) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - f.setTitle(f.getClass().getSimpleName()); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setSize(width, height); - f.setVisible(true); - } + SwingUtilities.invokeLater(() -> { + f.setTitle(f.getClass().getSimpleName()); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setSize(width, height); + f.setVisible(true); }); } } ///:~ diff --git a/net/mindview/util/TextFile.java b/net/mindview/util/TextFile.java index 2a25e199..bae7adf2 100644 --- a/net/mindview/util/TextFile.java +++ b/net/mindview/util/TextFile.java @@ -10,16 +10,13 @@ public class TextFile extends ArrayList { public static String read(String fileName) { StringBuilder sb = new StringBuilder(); try { - BufferedReader in= new BufferedReader(new FileReader( - new File(fileName).getAbsoluteFile())); - try { + try (BufferedReader in = new BufferedReader(new FileReader( + new File(fileName).getAbsoluteFile()))) { String s; while((s = in.readLine()) != null) { sb.append(s); sb.append("\n"); } - } finally { - in.close(); } } catch(IOException e) { throw new RuntimeException(e); @@ -29,12 +26,9 @@ public class TextFile extends ArrayList { // Write a single file in one method call: public static void write(String fileName, String text) { try { - PrintWriter out = new PrintWriter( - new File(fileName).getAbsoluteFile()); - try { + try (PrintWriter out = new PrintWriter( + new File(fileName).getAbsoluteFile())) { out.print(text); - } finally { - out.close(); } } catch(IOException e) { throw new RuntimeException(e); @@ -53,13 +47,10 @@ public class TextFile extends ArrayList { } public void write(String fileName) { try { - PrintWriter out = new PrintWriter( - new File(fileName).getAbsoluteFile()); - try { + try (PrintWriter out = new PrintWriter( + new File(fileName).getAbsoluteFile())) { for(String item : this) out.println(item); - } finally { - out.close(); } } catch(IOException e) { throw new RuntimeException(e); diff --git a/network/build.xml b/network/build.xml index a44233d7..47bbd754 100644 --- a/network/build.xml +++ b/network/build.xml @@ -6,7 +6,6 @@ - @@ -14,7 +13,6 @@ - diff --git a/object/build.xml b/object/build.xml index 36fa8182..698923bb 100644 --- a/object/build.xml +++ b/object/build.xml @@ -6,10 +6,8 @@ - - diff --git a/operators/EqualsMethod.java b/operators/EqualsMethod.java index fe4946d9..ac17824e 100644 --- a/operators/EqualsMethod.java +++ b/operators/EqualsMethod.java @@ -2,8 +2,8 @@ public class EqualsMethod { public static void main(String[] args) { - Integer n1 = new Integer(47); - Integer n2 = new Integer(47); + Integer n1 = 47; + Integer n2 = 47; System.out.println(n1.equals(n2)); } } /* Output: diff --git a/operators/Equivalence.java b/operators/Equivalence.java index 765abc84..bf3d6bd5 100644 --- a/operators/Equivalence.java +++ b/operators/Equivalence.java @@ -2,8 +2,8 @@ public class Equivalence { public static void main(String[] args) { - Integer n1 = new Integer(47); - Integer n2 = new Integer(47); + Integer n1 = 47; + Integer n2 = 47; System.out.println(n1 == n2); System.out.println(n1 != n2); } diff --git a/operators/build.xml b/operators/build.xml index 6156ba50..18db0b80 100644 --- a/operators/build.xml +++ b/operators/build.xml @@ -6,7 +6,6 @@ - @@ -28,7 +27,6 @@ - diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java index d60e8794..d9066fd8 100644 --- a/patterns/ShapeFactory2.java +++ b/patterns/ShapeFactory2.java @@ -79,9 +79,9 @@ public class ShapeFactory2 { "Square", "Circle", "Circle", "Square" }; ArrayList shapes = new ArrayList(); try { - for(int i = 0; i < shlist.length; i++) - shapes.add( - ShapeFactory.createShape(shlist[i])); + for (String shlist1 : shlist) { + shapes.add(ShapeFactory.createShape(shlist1)); + } } catch(BadShapeCreation e) { e.printStackTrace(); return; diff --git a/patterns/build.xml b/patterns/build.xml index 276d40d6..7caafa83 100644 --- a/patterns/build.xml +++ b/patterns/build.xml @@ -6,7 +6,6 @@ - @@ -30,7 +29,6 @@ - diff --git a/patterns/doubledispatch/DDAluminum.java b/patterns/doubledispatch/DDAluminum.java index 9bb9ecec..cfd13172 100644 --- a/patterns/doubledispatch/DDAluminum.java +++ b/patterns/doubledispatch/DDAluminum.java @@ -8,9 +8,11 @@ public class DDAluminum extends Aluminum public DDAluminum(double wt) { super(wt); } @Override public boolean addToBin(TypedBin[] tb) { - for(int i = 0; i < tb.length; i++) - if(tb[i].add(this)) + for (TypedBin tb1 : tb) { + if (tb1.add(this)) { return true; + } + } return false; } } ///:~ diff --git a/patterns/doubledispatch/DDCardboard.java b/patterns/doubledispatch/DDCardboard.java index f8713adf..8d38845a 100644 --- a/patterns/doubledispatch/DDCardboard.java +++ b/patterns/doubledispatch/DDCardboard.java @@ -8,9 +8,11 @@ public class DDCardboard extends Cardboard public DDCardboard(double wt) { super(wt); } @Override public boolean addToBin(TypedBin[] tb) { - for(int i = 0; i < tb.length; i++) - if(tb[i].add(this)) + for (TypedBin tb1 : tb) { + if (tb1.add(this)) { return true; + } + } return false; } } ///:~ diff --git a/patterns/doubledispatch/DDGlass.java b/patterns/doubledispatch/DDGlass.java index 573d2519..d2720c30 100644 --- a/patterns/doubledispatch/DDGlass.java +++ b/patterns/doubledispatch/DDGlass.java @@ -8,9 +8,11 @@ public class DDGlass extends Glass public DDGlass(double wt) { super(wt); } @Override public boolean addToBin(TypedBin[] tb) { - for(int i = 0; i < tb.length; i++) - if(tb[i].add(this)) + for (TypedBin tb1 : tb) { + if (tb1.add(this)) { return true; + } + } return false; } } ///:~ diff --git a/patterns/doubledispatch/DDPaper.java b/patterns/doubledispatch/DDPaper.java index 6b2feefd..9160e593 100644 --- a/patterns/doubledispatch/DDPaper.java +++ b/patterns/doubledispatch/DDPaper.java @@ -8,9 +8,11 @@ public class DDPaper extends Paper public DDPaper(double wt) { super(wt); } @Override public boolean addToBin(TypedBin[] tb) { - for(int i = 0; i < tb.length; i++) - if(tb[i].add(this)) + for (TypedBin tb1 : tb) { + if (tb1.add(this)) { return true; + } + } return false; } } ///:~ diff --git a/patterns/doubledispatch/DoubleDispatch.java b/patterns/doubledispatch/DoubleDispatch.java index 803e8185..68923ec1 100644 --- a/patterns/doubledispatch/DoubleDispatch.java +++ b/patterns/doubledispatch/DoubleDispatch.java @@ -63,8 +63,9 @@ public class DoubleDispatch { bins.sortIntoBins(bin); TypedBin[] tb = bins.binSet(); // Perform sumValue for each bin... - for(int i = 0; i < tb.length; i++) - Trash.sumValue(tb[i].v); + for (TypedBin tb1 : tb) { + Trash.sumValue(tb1.v); + } // ... and for the master bin Trash.sumValue(bin); } diff --git a/patterns/factory/ShapeFactory1.java b/patterns/factory/ShapeFactory1.java index 2ebd14e7..dd7499aa 100644 --- a/patterns/factory/ShapeFactory1.java +++ b/patterns/factory/ShapeFactory1.java @@ -50,8 +50,9 @@ public class ShapeFactory1 { "Square", "Circle", "Circle", "Square" }; ArrayList shapes = new ArrayList(); try { - for(int i = 0; i < shlist.length; i++) - shapes.add(Shape.factory(shlist[i])); + for (String shlist1 : shlist) { + shapes.add(Shape.factory(shlist1)); + } } catch(BadShapeCreation e) { e.printStackTrace(); return; diff --git a/patterns/trash/ParseTrash.java b/patterns/trash/ParseTrash.java index 2835ac44..eaf914ef 100644 --- a/patterns/trash/ParseTrash.java +++ b/patterns/trash/ParseTrash.java @@ -9,23 +9,22 @@ public class ParseTrash { public static void fillBin(String filename, Fillable bin) { try { - BufferedReader data = - new BufferedReader( - new FileReader(filename)); - String buf; - while((buf = data.readLine())!= null) { - if(buf.trim().length() == 0) - continue; // Skip empty lines - String type = buf.substring(0, - buf.indexOf(':')).trim(); - double weight = Double.valueOf( - buf.substring(buf.indexOf(':') + 1) - .trim()).doubleValue(); - bin.addTrash( - Trash.factory( - new Trash.Info(type, weight))); + try (BufferedReader data = new BufferedReader( + new FileReader(filename))) { + String buf; + while((buf = data.readLine())!= null) { + if(buf.trim().length() == 0) + continue; // Skip empty lines + String type = buf.substring(0, + buf.indexOf(':')).trim(); + double weight = Double.valueOf( + buf.substring(buf.indexOf(':') + 1) + .trim()); + bin.addTrash( + Trash.factory( + new Trash.Info(type, weight))); + } } - data.close(); } catch(IOException e) { e.printStackTrace(); } catch(Exception e) { diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java index 34509ec2..0db06d3d 100644 --- a/patterns/trash/Trash.java +++ b/patterns/trash/Trash.java @@ -39,22 +39,21 @@ public abstract class Trash { public static Trash factory(Info info) throws PrototypeNotFoundException, CannotCreateTrashException { - for(int i = 0; i < trashTypes.size(); i++) { + for (Object trashType : trashTypes) { // Somehow determine the new type // to create, and create one: - Class tc = - (Class)trashTypes.get(i); - if (tc.getName().indexOf(info.id) != -1) { + Class tc = (Class) trashType; + if (tc.getName().contains(info.id)) { try { // Get the dynamic constructor method // that takes a double argument: Constructor ctor = - tc.getConstructor( - new Class[] {double.class}); + tc.getConstructor( + new Class[] {double.class}); // Call the constructor to create a // new object: return (Trash)ctor.newInstance( - new Object[]{new Double(info.data)}); + new Object[]{info.data}); } catch(Exception ex) { ex.printStackTrace(); throw new CannotCreateTrashException(); diff --git a/polymorphism/build.xml b/polymorphism/build.xml index 5ec52f5f..76685bc9 100644 --- a/polymorphism/build.xml +++ b/polymorphism/build.xml @@ -6,7 +6,6 @@ - @@ -21,7 +20,6 @@ - diff --git a/references/CheckCloneable.java b/references/CheckCloneable.java index 0f10b954..e0f2a890 100644 --- a/references/CheckCloneable.java +++ b/references/CheckCloneable.java @@ -84,7 +84,8 @@ public class CheckCloneable { // This won't compile; clone() is protected in Object: //! x = (Ordinary)x.clone(); // Checks first to see if a class implements Cloneable: - for(int i = 0; i < ord.length; i++) - tryToClone(ord[i]); + for (Ordinary ord1 : ord) { + tryToClone(ord1); + } } } ///:~ diff --git a/references/Compete.java b/references/Compete.java index 0689c266..7c3af4d2 100644 --- a/references/Compete.java +++ b/references/Compete.java @@ -47,8 +47,9 @@ public class Compete { long t1 = System.currentTimeMillis(); ByteArrayOutputStream buf= new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); - for(int i = 0; i < a.length; i++) - o.writeObject(a[i]); + for (Thing2 a1 : a) { + o.writeObject(a1); + } // Now get copies: ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(buf.toByteArray())); diff --git a/references/build.xml b/references/build.xml index 2da6f359..e6295a68 100644 --- a/references/build.xml +++ b/references/build.xml @@ -6,7 +6,6 @@ - @@ -25,7 +24,6 @@ - diff --git a/remote/build.xml b/remote/build.xml index 94da2ef0..ade93e83 100644 --- a/remote/build.xml +++ b/remote/build.xml @@ -6,8 +6,6 @@ - - diff --git a/reusing/build.xml b/reusing/build.xml index 7fb8da0f..d125b521 100644 --- a/reusing/build.xml +++ b/reusing/build.xml @@ -6,7 +6,6 @@ - @@ -26,7 +25,6 @@ - diff --git a/strings/WhitherStringBuilder.java b/strings/WhitherStringBuilder.java index 1cef4f6b..50e4e055 100644 --- a/strings/WhitherStringBuilder.java +++ b/strings/WhitherStringBuilder.java @@ -3,14 +3,16 @@ public class WhitherStringBuilder { public String implicit(String[] fields) { String result = ""; - for(int i = 0; i < fields.length; i++) - result += fields[i]; + for (String field : fields) { + result += field; + } return result; } public String explicit(String[] fields) { StringBuilder result = new StringBuilder(); - for(int i = 0; i < fields.length; i++) - result.append(fields[i]); + for (String field : fields) { + result.append(field); + } return result.toString(); } } ///:~ diff --git a/strings/build.xml b/strings/build.xml index 2f4b4eea..1d992076 100644 --- a/strings/build.xml +++ b/strings/build.xml @@ -6,7 +6,6 @@ - @@ -35,7 +34,6 @@ - diff --git a/swt/ShellsAreMainWindows.java b/swt/ShellsAreMainWindows.java index ce519d86..29bee835 100644 --- a/swt/ShellsAreMainWindows.java +++ b/swt/ShellsAreMainWindows.java @@ -16,9 +16,11 @@ public class ShellsAreMainWindows { display.dispose(); } static boolean shellsDisposed() { - for(int i = 0; i < shells.length; i++) - if(shells[i].isDisposed()) + for (Shell shell : shells) { + if (shell.isDisposed()) { return true; + } + } return false; } } ///:~ diff --git a/swt/build.xml b/swt/build.xml index fbd57d62..cbd0e50d 100644 --- a/swt/build.xml +++ b/swt/build.xml @@ -6,7 +6,6 @@ - @@ -15,7 +14,6 @@ - diff --git a/typeinfo/ShowMethods.java b/typeinfo/ShowMethods.java index 0e58f4bd..8564ba2e 100644 --- a/typeinfo/ShowMethods.java +++ b/typeinfo/ShowMethods.java @@ -33,13 +33,13 @@ public class ShowMethods { lines = methods.length + ctors.length; } else { for(Method method : methods) - if(method.toString().indexOf(args[1]) != -1) { + if(method.toString().contains(args[1])) { print( p.matcher(method.toString()).replaceAll("")); lines++; } for(Constructor ctor : ctors) - if(ctor.toString().indexOf(args[1]) != -1) { + if(ctor.toString().contains(args[1])) { print(p.matcher( ctor.toString()).replaceAll("")); lines++; diff --git a/typeinfo/build.xml b/typeinfo/build.xml index 2473e972..25452e3f 100644 --- a/typeinfo/build.xml +++ b/typeinfo/build.xml @@ -6,7 +6,6 @@ - @@ -36,7 +35,6 @@ - diff --git a/unittesting/build.xml b/unittesting/build.xml index 66bc77c8..9c8d3f37 100644 --- a/unittesting/build.xml +++ b/unittesting/build.xml @@ -6,9 +6,7 @@ - - diff --git a/xml/build.xml b/xml/build.xml index a9420cf4..0cb36772 100644 --- a/xml/build.xml +++ b/xml/build.xml @@ -6,10 +6,8 @@ - -