Code refactoring for Java 8

This commit is contained in:
Bruce Eckel 2015-05-06 12:09:38 -07:00
parent f9d1be83be
commit 3e0098ae73
64 changed files with 218 additions and 148 deletions

View File

@ -23,8 +23,8 @@
<attribute name="timeOut" default="15000"/>
<attribute name="msg" default=""/>
<sequential>
<echo>Running: ${chapter} @{cls}&#13;</echo>
<echo file="${antoutput}" append="true">Running: ${chapter} @{cls}&#13;</echo>
<echo>[${chapter}] Running: java @{cls} @{arguments}&#13;</echo>
<echo file="${antoutput}" append="true">[${chapter}] Running: java @{cls} @{arguments}&#13;</echo>
<java
classname="@{cls}"
classpath="${java.class.path};${basedir};${basedir}/.."
@ -35,7 +35,7 @@
output="${antoutput}" append="true">
<arg line="@{arguments}"/>
</java>
<echo file="${antoutput}" append="true">Finished: ${chapter} @{cls}&#13;</echo>
<echo file="${antoutput}" append="true">[${chapter}] Finished: java @{cls} @{arguments}&#13;</echo>
<echo file="${antoutput}" append="true">@{msg}&#13;</echo>
<echo file="${antoutput}" append="true">--------------------------------&#13;</echo>
</sequential>
@ -49,8 +49,8 @@
<attribute name="timeOut" default="15000"/>
<attribute name="msg" default=""/>
<sequential>
<echo>Running: ${chapter} @{cls}&#13;</echo>
<echo append="true">Running: ${chapter} @{cls}&#13;</echo>
<echo>[${chapter}] Running: java @{cls} @{arguments}&#13;</echo>
<echo append="true">[${chapter}] Running: java @{cls} @{arguments}&#13;</echo>
<java
classname="@{cls}"
classpath="${java.class.path};${basedir};${basedir}/.."
@ -61,7 +61,7 @@
>
<arg line="@{arguments}"/>
</java>
<echo append="true">Finished: ${chapter} @{cls}&#13;</echo>
<echo append="true">[${chapter}] Finished: java @{cls} @{arguments}&#13;</echo>
<echo append="true">@{msg}&#13;</echo>
<echo append="true">--------------------------------&#13;</echo>
</sequential>

View File

@ -11,7 +11,8 @@ public class GeneratorsTest {
for(int i = 0; i < size; i++)
System.out.printf(g.next() + " ");
System.out.println();
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -52,7 +52,8 @@ public class ActiveObjectDemo {
if(f.isDone()) {
try {
print(f.get());
} catch(Exception e) {
} catch(InterruptedException |
ExecutionException e) {
throw new RuntimeException(e);
}
results.remove(f);

View File

@ -137,12 +137,10 @@ public class GreenhouseScheduler {
if(rand.nextInt(5) == 4)
tempDirection = -tempDirection;
// Store previous value:
lastTemp = lastTemp +
tempDirection * (1.0f + rand.nextFloat());
lastTemp += tempDirection * (1.0f + rand.nextFloat());
if(rand.nextInt(5) == 4)
humidityDirection = -humidityDirection;
lastHumidity = lastHumidity +
humidityDirection * rand.nextFloat();
lastHumidity += humidityDirection * rand.nextFloat();
// Calendar must be cloned, otherwise all
// DataPoints hold references to the same lastTime.
// For a basic object like Calendar, clone() is OK.

View File

@ -35,7 +35,7 @@ class Blocked3 implements Runnable {
print("Calculating");
// A time-consuming, non-blocking operation:
for(int i = 1; i < 2500000; i++)
d = d + (Math.PI + Math.E) / d;
d += (Math.PI + Math.E) / d;
print("Finished time-consuming operation");
} finally {
n2.cleanup();

View File

@ -18,7 +18,8 @@ public class Pool<T> {
try {
// Assumes a default constructor:
items.add(classObject.newInstance());
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -6,7 +6,7 @@ class UnresponsiveUI {
private volatile double d = 1;
public UnresponsiveUI() throws Exception {
while(d > 0)
d = d + (Math.PI + Math.E) / d;
d += (Math.PI + Math.E) / d;
System.in.read(); // Never gets here
}
}
@ -20,7 +20,7 @@ public class ResponsiveUI extends Thread {
@Override
public void run() {
while(true) {
d = d + (Math.PI + Math.E) / d;
d += (Math.PI + Math.E) / d;
}
}
public static void main(String[] args) throws Exception {

View File

@ -35,7 +35,8 @@ abstract class Accumulator {
accumulate();
try {
barrier.await();
} catch(Exception e) {
} catch(InterruptedException |
BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
@ -48,7 +49,8 @@ abstract class Accumulator {
value = read();
try {
barrier.await();
} catch(Exception e) {
} catch(InterruptedException |
BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
@ -61,7 +63,8 @@ abstract class Accumulator {
}
try {
barrier.await();
} catch(Exception e) {
} catch(InterruptedException |
BrokenBarrierException e) {
throw new RuntimeException(e);
}
duration = System.nanoTime() - start;

View File

@ -44,7 +44,7 @@ public class CountedString {
CountedString[] cs = new CountedString[5];
for(int i = 0; i < cs.length; i++) {
cs[i] = new CountedString("hi");
map.put(cs[i], i); // Autobox int -> Integer
map.put(cs[i], i); // Autobox int to Integer
}
print(map);
for(CountedString cstring : cs) {

View File

@ -1,5 +1,6 @@
//: containers/TypesForSets.java
// Methods necessary to put your own type in a Set.
import java.lang.reflect.InvocationTargetException;
import java.util.*;
class SetType {
@ -34,7 +35,12 @@ public class TypesForSets {
for(int i = 0; i < 10; i++)
set.add(
type.getConstructor(int.class).newInstance(i));
} catch(Exception e) {
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
throw new RuntimeException(e);
}
return set;

View File

@ -5,13 +5,13 @@ public class StringSwitch {
public static void main(String[] args) {
String color = "red";
// Old way: using if-then
if(color == "red") {
if("red".equals(color)) {
print("RED");
} else if(color == "green") {
} else if("green".equals(color)) {
print("GREEN");
} else if(color == "blue") {
} else if("blue".equals(color)) {
print("BLUE");
} else if(color == "yellow") {
} else if("yellow".equals(color)) {
print("YELLOW");
} else {
print("Unknown");

View File

@ -11,12 +11,8 @@ public class EnumMaps {
public static void main(String[] args) {
EnumMap<AlarmPoints,Command> em =
new EnumMap<>(AlarmPoints.class);
em.put(KITCHEN, (Command) () -> {
print("Kitchen fire!");
});
em.put(BATHROOM, (Command) () -> {
print("Bathroom alert!");
});
em.put(KITCHEN, () -> print("Kitchen fire!"));
em.put(BATHROOM, () -> print("Bathroom alert!"));
for(Map.Entry<AlarmPoints,Command> e : em.entrySet()) {
printnb(e.getKey() + ": ");
e.getValue().action();

View File

@ -93,9 +93,8 @@ public class DynamicFields {
print("df: " + df);
print("df.getField(\"d\") : " + df.getField("d"));
Object field = df.setField("d", null); // Exception
} catch(NoSuchFieldException e) {
e.printStackTrace(System.out);
} catch(DynamicFieldsException e) {
} catch(NoSuchFieldException |
DynamicFieldsException e) {
e.printStackTrace(System.out);
}
}

View File

@ -30,7 +30,8 @@ public class LostMessage {
} finally {
lm.dispose();
}
} catch(Exception e) {
} catch(VeryImportantException |
HoHumException e) {
System.out.println(e);
}
}

View File

@ -12,7 +12,8 @@ class WrapCheckedException {
case 2: throw new RuntimeException("Where am I?");
default: return;
}
} catch(Exception e) { // Adapt to unchecked:
} catch(IOException | RuntimeException e) {
// Adapt to unchecked:
throw new RuntimeException(e);
}
}

View File

@ -10,7 +10,9 @@ public class Apply {
try {
for(T t: seq)
f.invoke(t, args);
} catch(Exception e) {
} catch(IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
// Failures are programmer errors
throw new RuntimeException(e);
}
@ -32,7 +34,8 @@ class FilledList<T> extends ArrayList<T> {
for(int i = 0; i < size; i++)
// Assumes default constructor:
add(type.newInstance());
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -14,7 +14,8 @@ public class Fill {
// Assumes default constructor:
try {
collection.add(classToken.newInstance());
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -15,7 +15,8 @@ public class Fill2 {
for(int i = 0; i < size; i++)
try {
addable.add(classToken.newInstance());
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -24,7 +24,9 @@ public class GenericArray2<T> {
System.out.println();
try {
Integer[] ia = gai.rep();
} catch(Exception e) { System.out.println(e); }
} catch(Exception e) {
System.out.println(e);
}
}
} /* Output: (Sample)
0 1 2 3 4 5 6 7 8 9

View File

@ -6,7 +6,8 @@ class ClassAsFactory<T> {
public ClassAsFactory(Class<T> kind) {
try {
x = kind.newInstance();
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -35,7 +35,10 @@ class CommunicateReflectively {
} catch(NoSuchMethodException e) {
print(speaker + " cannot sit");
}
} catch(Exception e) {
} catch(SecurityException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
throw new RuntimeException(speaker.toString(), e);
}
}

View File

@ -19,7 +19,8 @@ implements Generator<Coffee>, Iterable<Coffee> {
return (Coffee)
types[rand.nextInt(types.length)].newInstance();
// Report programmer errors at run time:
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -10,7 +10,7 @@ public class Button2b extends JFrame {
b1 = new JButton("Button 1"),
b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
private ActionListener bl = (ActionEvent e) -> {
private ActionListener bl = e -> {
String name1 = ((JButton)e.getSource()).getText();
txt.setText(name1);
};

View File

@ -27,7 +27,12 @@ public class ButtonGroups extends JFrame {
kind.getConstructor(String.class);
// Create a new object:
ab = (AbstractButton)ctor.newInstance(id);
} catch(Exception ex) {
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException ex) {
System.err.println("can't create " + kind);
}
bg.add(ab);

View File

@ -12,15 +12,9 @@ public class CheckBoxes extends JFrame {
cb2 = new JCheckBox("Check Box 2"),
cb3 = new JCheckBox("Check Box 3");
public CheckBoxes() {
cb1.addActionListener((ActionEvent e) -> {
trace("1", cb1);
});
cb2.addActionListener((ActionEvent e) -> {
trace("2", cb2);
});
cb3.addActionListener((ActionEvent e) -> {
trace("3", cb3);
});
cb1.addActionListener(e -> trace("1", cb1));
cb2.addActionListener(e -> trace("2", cb2));
cb3.addActionListener(e -> trace("3", cb3));
setLayout(new FlowLayout());
add(new JScrollPane(t));
add(cb1);

View File

@ -11,18 +11,18 @@ public class ComboBoxes extends JFrame {
"Somnescent", "Timorous", "Florid", "Putrescent"
};
private JTextField t = new JTextField(15);
private JComboBox c = new JComboBox();
private JComboBox<String> c = new JComboBox<>();
private JButton b = new JButton("Add items");
private int count = 0;
public ComboBoxes() {
for(int i = 0; i < 4; i++)
c.addItem(description[count++]);
t.setEditable(false);
b.addActionListener((ActionEvent e) -> {
b.addActionListener(e -> {
if(count < description.length)
c.addItem(description[count++]);
});
c.addActionListener((ActionEvent e) -> {
c.addActionListener(e -> {
t.setText("index: "+ c.getSelectedIndex() + " " +
((JComboBox)e.getSource()).getSelectedItem());
});

View File

@ -11,9 +11,8 @@ class MyDialog extends JDialog {
setLayout(new FlowLayout());
add(new JLabel("Here is my dialog"));
JButton ok = new JButton("OK");
ok.addActionListener((ActionEvent e) -> {
dispose(); // Closes the dialog
});
ok.addActionListener(e ->
dispose()); // Closes the dialog
add(ok);
setSize(150,125);
}
@ -23,9 +22,7 @@ public class Dialogs extends JFrame {
private JButton b1 = new JButton("Dialog Box");
private MyDialog dlg = new MyDialog(null);
public Dialogs() {
b1.addActionListener((ActionEvent e) -> {
dlg.setVisible(true);
});
b1.addActionListener(e -> dlg.setVisible(true));
add(b1);
}
public static void main(String[] args) {

View File

@ -19,7 +19,7 @@ public class Faces extends JFrame {
};
jb = new JButton("JButton", faces[3]);
setLayout(new FlowLayout());
jb.addActionListener((ActionEvent e) -> {
jb.addActionListener(e -> {
if(mad) {
jb.setIcon(faces[3]);
mad = false;
@ -36,7 +36,7 @@ public class Faces extends JFrame {
jb.setDisabledIcon(faces[4]);
jb.setToolTipText("Yow!");
add(jb);
jb2.addActionListener((ActionEvent e) -> {
jb2.addActionListener(e -> {
if(jb.isEnabled()) {
jb.setEnabled(false);
jb2.setText("Enable");

View File

@ -10,7 +10,7 @@ public class HTMLButton extends JFrame {
"<html><b><font size=+2>" +
"<center>Hello!<br><i>Press me now!");
public HTMLButton() {
b.addActionListener((ActionEvent e) -> {
b.addActionListener(e -> {
add(new JLabel("<html>" +
"<i><font size=+4>Kapow!"));
// Force a re-layout to include the new label:

View File

@ -25,16 +25,16 @@ InterruptableLongRunningCallable extends JFrame {
private TaskManager<String,CallableTask> manager =
new TaskManager<>();
public InterruptableLongRunningCallable() {
b1.addActionListener((ActionEvent e) -> {
b1.addActionListener(e -> {
CallableTask task = new CallableTask();
manager.add(task);
System.out.println(task + " added to the queue");
});
b2.addActionListener((ActionEvent e) -> {
b2.addActionListener(e -> {
for(String result : manager.purge())
System.out.println(result);
});
b3.addActionListener((ActionEvent e) -> {
b3.addActionListener(e -> {
// Sample call to a Task method:
for(TaskItem<String,CallableTask> tt : manager)
tt.task.id(); // No cast required

View File

@ -32,12 +32,12 @@ public class InterruptableLongRunningTask extends JFrame {
ExecutorService executor =
Executors.newSingleThreadExecutor();
public InterruptableLongRunningTask() {
b1.addActionListener((ActionEvent e) -> {
b1.addActionListener(e -> {
Task task = new Task();
executor.execute(task);
System.out.println(task + " added to the queue");
});
b2.addActionListener((ActionEvent e) -> {
b2.addActionListener(e -> {
executor.shutdownNow(); // Heavy-handed
});
setLayout(new FlowLayout());

View File

@ -13,12 +13,13 @@ public class List extends JFrame {
"Praline Cream", "Mud Pie"
};
private int count = 0;
private DefaultListModel lItems = new DefaultListModel();
private JList lst = new JList(lItems);
private DefaultListModel<String> lItems =
new DefaultListModel<>();
private JList<String> lst = new JList<>(lItems);
private JTextArea t =
new JTextArea(flavors.length, 20);
private JButton b = new JButton("Add Item");
private ActionListener bl = (ActionEvent e) -> {
private ActionListener bl = e -> {
if(count < flavors.length) {
lItems.add(0, flavors[count++]);
} else {
@ -27,12 +28,11 @@ public class List extends JFrame {
b.setEnabled(false);
}
};
private ListSelectionListener ll =
(ListSelectionEvent e) -> {
if(e.getValueIsAdjusting()) return;
t.setText("");
for(Object item : lst.getSelectedValues())
t.append(item + "\n");
private ListSelectionListener ll = e -> {
if(e.getValueIsAdjusting()) return;
t.setText("");
for(Object item : lst.getSelectedValuesList())
t.append(item + "\n");
};
public List() {
t.setEditable(false);

View File

@ -11,16 +11,16 @@ public class LongRunningTask extends JFrame {
b1 = new JButton("Start Long Running Task"),
b2 = new JButton("End Long Running Task");
public LongRunningTask() {
b1.addActionListener((ActionEvent evt) -> {
b1.addActionListener(e -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch(InterruptedException e) {
} catch(InterruptedException ex) {
System.out.println("Task interrupted");
return;
}
System.out.println("Task completed");
});
b2.addActionListener((ActionEvent evt) -> {
b2.addActionListener(e -> {
// Interrupt yourself?
Thread.currentThread().interrupt();
});

View File

@ -14,8 +14,8 @@ public class LookAndFeel extends JFrame {
new JLabel("JLabel"),
new JCheckBox("JCheckBox"),
new JRadioButton("Radio"),
new JComboBox(choices),
new JList(choices),
new JComboBox<String>(choices),
new JList<String>(choices),
};
public LookAndFeel() {
super("Look And Feel");
@ -35,7 +35,10 @@ public class LookAndFeel extends JFrame {
try {
UIManager.setLookAndFeel(UIManager.
getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
} catch(ClassNotFoundException |
InstantiationException |
IllegalAccessException |
UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
break;
@ -43,7 +46,10 @@ public class LookAndFeel extends JFrame {
try {
UIManager.setLookAndFeel(UIManager.
getSystemLookAndFeelClassName());
} catch(Exception e) {
} catch(ClassNotFoundException |
InstantiationException |
IllegalAccessException |
UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
break;
@ -51,7 +57,10 @@ public class LookAndFeel extends JFrame {
try {
UIManager.setLookAndFeel("com.sun.java."+
"swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
} catch(ClassNotFoundException |
InstantiationException |
IllegalAccessException |
UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
break;

View File

@ -12,7 +12,7 @@ public class MessageBoxes extends JFrame {
new JButton("3 Vals")
};
private JTextField txt = new JTextField(15);
private ActionListener al = (ActionEvent e) -> {
private ActionListener al = e -> {
String id = ((JButton)e.getSource()).getText();
switch (id) {
case "Alert":

View File

@ -51,7 +51,7 @@ public class MonitoredLongRunningCallable extends JFrame {
private TaskManager<String,MonitoredCallable> manager =
new TaskManager<>();
public MonitoredLongRunningCallable() {
b1.addActionListener((ActionEvent e) -> {
b1.addActionListener(e -> {
MonitoredCallable task = new MonitoredCallable(
new ProgressMonitor(
MonitoredLongRunningCallable.this,
@ -60,11 +60,11 @@ public class MonitoredLongRunningCallable extends JFrame {
manager.add(task);
System.out.println(task + " added to the queue");
});
b2.addActionListener((ActionEvent e) -> {
b2.addActionListener(e -> {
for(String result : manager.purge())
System.out.println(result);
});
b3.addActionListener((ActionEvent e) -> {
b3.addActionListener(e -> {
for(String result : manager.getResults())
System.out.println(result);
});

View File

@ -11,9 +11,8 @@ public class Popup extends JFrame {
public Popup() {
setLayout(new FlowLayout());
add(t);
ActionListener al = (ActionEvent e) -> {
ActionListener al = e ->
t.setText(((JMenuItem)e.getSource()).getText());
};
JMenuItem m = new JMenuItem("Hither");
m.addActionListener(al);
popup.add(m);

View File

@ -24,9 +24,8 @@ public class Progress extends JFrame {
sb.setBorder(new TitledBorder("Slide Me"));
pb.setModel(sb.getModel()); // Share model
add(sb);
sb.addChangeListener((ChangeEvent e) -> {
pm.setProgress(sb.getValue());
});
sb.addChangeListener(e ->
pm.setProgress(sb.getValue()));
}
public static void main(String[] args) {
run(new Progress(), 300, 200);

View File

@ -12,10 +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 = (ActionEvent e) -> {
private ActionListener al = e ->
t.setText("Radio button " +
((JRadioButton)e.getSource()).getText());
};
public RadioButtons() {
rb1.addActionListener(al);
rb2.addActionListener(al);

View File

@ -6,9 +6,8 @@ import static net.mindview.util.SwingConsole.*;
public class SimpleMenus extends JFrame {
private JTextField t = new JTextField(15);
private ActionListener al = (ActionEvent e) -> {
private ActionListener al = e ->
t.setText(((JMenuItem)e.getSource()).getText());
};
private JMenu[] menus = {
new JMenu("Winken"), new JMenu("Blinken"),
new JMenu("Nod")

View File

@ -11,8 +11,7 @@ public class SubmitLabelManipulationTask {
frame.setSize(300, 100);
frame.setVisible(true);
TimeUnit.SECONDS.sleep(1);
SwingUtilities.invokeLater(() -> {
label.setText("Hey! This is Different!");
});
SwingUtilities.invokeLater(() ->
label.setText("Hey! This is Different!"));
}
} ///:~

View File

@ -14,12 +14,10 @@ public class SubmitSwingProgram extends JFrame {
}
static SubmitSwingProgram ssp;
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(() -> {
ssp = new SubmitSwingProgram();
});
SwingUtilities.invokeLater(() ->
ssp = new SubmitSwingProgram());
TimeUnit.SECONDS.sleep(1);
SwingUtilities.invokeLater(() -> {
ssp.label.setText("Hey! This is Different!");
});
SwingUtilities.invokeLater(() ->
ssp.label.setText("Hey! This is Different!"));
}
} ///:~

View File

@ -18,10 +18,9 @@ public class TabbedPane1 extends JFrame {
for(String flavor : flavors)
tabs.addTab(flavors[i],
new JButton("Tabbed pane " + i++));
tabs.addChangeListener((ChangeEvent e) -> {
tabs.addChangeListener(e ->
txt.setText("Tab selected: " +
tabs.getSelectedIndex());
});
tabs.getSelectedIndex()));
add(BorderLayout.SOUTH, txt);
add(tabs);
}

View File

@ -16,13 +16,11 @@ public class TextArea extends JFrame {
public TextArea() {
// Use up all the data:
m.putAll(Countries.capitals());
b.addActionListener((ActionEvent e) -> {
b.addActionListener(e -> {
for(Map.Entry me : m.entrySet())
t.append(me.getKey() + ": "+ me.getValue()+"\n");
});
c.addActionListener((ActionEvent e) -> {
t.setText("");
});
c.addActionListener(e -> t.setText(""));
setLayout(new FlowLayout());
add(new JScrollPane(t));
add(b);

View File

@ -12,7 +12,7 @@ public class TextPane extends JFrame {
private static Generator sg =
new RandomGenerator.String(7);
public TextPane() {
b.addActionListener((ActionEvent e) -> {
b.addActionListener(e -> {
for(int i = 1; i < 10; i++)
tp.setText(tp.getText() + sg.next() + "\n");
});

View File

@ -7,7 +7,7 @@ public class ArraysOfPrimitives {
int[] a2;
a2 = a1;
for(int i = 0; i < a2.length; i++)
a2[i] = a2[i] + 1;
a2[i] += 1;
for(int i = 0; i < a1.length; i++)
print("a1[" + i + "] = " + a1[i]);
}

View File

@ -1,15 +1,41 @@
//: innerclasses/LambdaExpressions.java
import static net.mindview.util.Print.*;
interface Description {
String brief();
}
interface Body {
String detailed(String head);
}
interface Multi {
String twoArg(String head, Double d);
}
public class LambdaExpressions {
Description desc = new Description() {
@Override
public String brief() {
return "Short info";
public String brief() {
return "Short info";
}
};
Description desc2 = () -> "Short info";
Description desc2 = () -> "Short info";
Body bod = (h) -> h + " More details";
Body bod2 = h -> h + " No Parens!";
Multi mult = (h, n) -> h + n;
// Parens are required with multiple args:
// Multi mult2 = h, n -> h + n; // Nope
public static void main(String[] args) {
LambdaExpressions le =
new LambdaExpressions();
print(le.desc.brief());
print(le.desc2.brief());
print(le.bod.detailed("Hi!"));
print(le.bod2.detailed("Oh!"));
print(le.mult.twoArg("Pi! ", 3.14159));
}
} ///:~

View File

@ -17,6 +17,7 @@
<jrun cls="Games" />
<jrun cls="GreenhouseController" arguments='5000' />
<jrun cls="InheritInner" />
<jrun cls="LambdaExpressions" />
<jrun cls="LocalInnerClass" />
<jrun cls="innerclasses.MultiImplementation" dirpath="../innerclasses" />
<jrun cls="innerclasses.MultiInterfaces" dirpath="../innerclasses" />

View File

@ -34,7 +34,7 @@ public class AtUnit implements ProcessFiles.Strategy {
if(!cName.contains("."))
return; // Ignore unpackaged classes
testClass = Class.forName(cName);
} catch(Exception e) {
} catch(IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
TestMethods testMethods = new TestMethods();
@ -86,7 +86,9 @@ public class AtUnit implements ProcessFiles.Strategy {
}
if(cleanup != null)
cleanup.invoke(testObject, testObject);
} catch(Exception e) {
} catch(IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
throw new RuntimeException(e);
}
}
@ -137,14 +139,17 @@ public class AtUnit implements ProcessFiles.Strategy {
if(creator != null) {
try {
return creator.invoke(testClass);
} catch(Exception e) {
} catch(IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
throw new RuntimeException("Couldn't run " +
"@TestObject (creator) method.");
}
} else { // Use the default constructor:
try {
return testClass.newInstance();
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException("Couldn't create a " +
"test object. Try using a @TestObject method.");
}

View File

@ -58,7 +58,7 @@ public class ClassNameFinder {
int super_class = data.readShort();
return classNameTable.get(
offsetTable.get(this_class)).replace('/', '.');
} catch(Exception e) {
} catch(IOException | RuntimeException e) {
throw new RuntimeException(e);
}
}

View File

@ -11,7 +11,8 @@ public class BasicGenerator<T> implements Generator<T> {
try {
// Assumes type is a public class:
return type.newInstance();
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}

View File

@ -41,8 +41,7 @@ public class ProcessFiles {
}
// Demonstration of how to use it:
public static void main(String[] args) {
new ProcessFiles((File file) -> {
System.out.println(file);
}, "java").start(args);
new ProcessFiles(file -> System.out.println(file),
"java").start(args);
}
} /* (Execute to see output) *///:~

View File

@ -19,7 +19,8 @@ extends ArrayList<TaskItem<R,C>> {
if(item.future.isDone()) {
try {
results.add(item.future.get());
} catch(Exception e) {
} catch(InterruptedException |
ExecutionException e) {
throw new RuntimeException(e);
}
items.remove();

View File

@ -2,7 +2,6 @@
// {TimeOutDuringTesting}
// Tests the ChatterServer by starting multiple
// clients, each of which sends datagrams.
import java.lang.Thread;
import java.net.*;
import java.io.*;

View File

@ -79,7 +79,7 @@ public class MultiSimpleClient {
if(SimpleClientThread.threadCount()
< MAX_THREADS)
new SimpleClientThread(addr);
Thread.currentThread().sleep(100);
Thread.sleep(100);
}
}
} ///:~

View File

@ -14,8 +14,8 @@ abstract class Shape {
public abstract void erase();
static Shape factory(String type)
throws BadShapeCreation {
if(type == "Circle") return new Circle();
if(type == "Square") return new Square();
if("Circle".equals(type)) return new Circle();
if("Square".equals(type)) return new Square();
throw new BadShapeCreation(type);
}
}

View File

@ -27,7 +27,9 @@ public class ParseTrash {
}
} catch(IOException e) {
e.printStackTrace();
} catch(Exception e) {
} catch(NumberFormatException |
Trash.PrototypeNotFoundException |
Trash.CannotCreateTrashException e) {
e.printStackTrace();
}
}

View File

@ -54,7 +54,12 @@ public abstract class Trash {
// new object:
return (Trash)ctor.newInstance(
new Object[]{info.data});
} catch(Exception ex) {
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException ex) {
ex.printStackTrace();
throw new CannotCreateTrashException();
}

View File

@ -23,7 +23,7 @@ class StaticSub extends StaticSuper {
public class StaticPolymorphism {
public static void main(String[] args) {
StaticSuper sup = new StaticSub(); // Upcast
System.out.println(sup.staticGet());
System.out.println(StaticSuper.staticGet());
System.out.println(sup.dynamicGet());
}
} /* Output:

View File

@ -123,8 +123,14 @@ public class CopyConstructor {
Object obj = ct.newInstance(new Object[] { t });
System.out.println("In ripen2, t is a " +
obj.getClass().getName());
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
System.out.println(e);
}
catch(Exception e) { System.out.println(e); }
}
public static void slice2(Fruit f) {
try {
@ -133,8 +139,14 @@ public class CopyConstructor {
Object obj = ct.newInstance(new Object[] { f });
System.out.println("In slice2, f is a " +
obj.getClass().getName());
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException e) {
System.out.println(e);
}
catch(Exception e) { System.out.println(e); }
}
public static void main(String[] args) {
Tomato tomato = new Tomato();

View File

@ -2,6 +2,7 @@
// Uses remote object PerfectTime
// {RunByHand}
package remote.ptime;
import java.net.MalformedURLException;
import java.rmi.*;
import java.rmi.registry.*;
@ -15,7 +16,9 @@ public class DisplayPerfectTime {
for(int i = 0; i < 10; i++)
System.out.println("Perfect time = " +
t.getPerfectTime());
} catch(Exception e) {
} catch(NotBoundException |
MalformedURLException |
RemoteException e) {
e.printStackTrace();
}
}

View File

@ -30,7 +30,9 @@ public class PerfectTime
Naming.bind(
"//MindviewToshibaLaptop:2005/PerfectTime", pt);
System.out.println("Ready to do time");
} catch(Exception e) {
} catch(RemoteException |
AlreadyBoundException |
MalformedURLException e) {
e.printStackTrace();
}
}

View File

@ -16,7 +16,8 @@ public class FilledList<T> {
try {
for(int i = 0; i < nElements; i++)
result.add(type.newInstance());
} catch(Exception e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
return result;

View File

@ -11,9 +11,8 @@ public abstract class PetCreator {
int n = rand.nextInt(types().size());
try {
return types().get(n).newInstance();
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}