More Netbeans mods

This commit is contained in:
Bruce Eckel 2015-05-05 14:05:39 -07:00
parent 7175059a16
commit f5a2dd0e00
108 changed files with 474 additions and 685 deletions

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="Cake" />
<jrun cls="ChocolateChip" />
<jrun cls="ChocolateChip2" />
@ -18,7 +17,6 @@
<jrun cls="PrintTest" />
<jrun cls="QualifiedMyClass" />
<jrun cls="SingleImport" />
<delete file="failures"/>
</target>
</project>

View File

@ -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);
}

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="annotations.AtUnitComposition" dirpath="../annotations" />
<jrun cls="annotations.AtUnitExample1" dirpath="../annotations" />
<jrun cls="annotations.AtUnitExample2" dirpath="../annotations" />
@ -19,7 +18,6 @@
<jrun cls="annotations.StackLStringTest" dirpath="../annotations" />
<jrun cls="UseCaseTracker" />
<jrun cls="annotations.database.TableCreator" dirpath="../annotations/database" arguments='annotations.database.Member' />
<delete file="failures"/>
</target>
</project>

View File

@ -25,12 +25,7 @@ public class CompType implements Comparable<CompType> {
}
private static Random r = new Random(47);
public static Generator<CompType> generator() {
return new Generator<CompType>() {
@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 =

View File

@ -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);

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AlphabeticSearch" />
<jrun cls="ArrayOfGenerics" />
<jrun cls="ArrayOptions" />
@ -33,7 +32,6 @@
<jrun cls="TestArrayGeneration" />
<jrun cls="TestGenerated" />
<jrun cls="ThreeDWithNew" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,12 +6,10 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="Assert1" failOnError='false' msg='* Exception was Expected *' />
<jrun cls="Assert2" failOnError='false' msg='* Exception was Expected *' />
<jrun cls="LoaderAssertions" failOnError='false' msg='* Exception was Expected *' />
<jrun cls="Queue" />
<delete file="failures"/>
</target>
</project>

View File

@ -22,24 +22,18 @@ public class ActiveObjectDemo {
}
public Future<Integer>
calculateInt(final int x, final int y) {
return ex.submit(new Callable<Integer>() {
@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<Float>
calculateFloat(final float x, final float y) {
return ex.submit(new Callable<Float>() {
@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(); }

View File

@ -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

View File

@ -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++) {

View File

@ -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

View File

@ -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);

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="ActiveObjectDemo" />
<jrun cls="AtomicEvenGenerator" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="AtomicIntegerTest" />
@ -74,7 +73,6 @@
<jrun cls="concurrency.restaurant2.RestaurantWithQueues" dirpath="../concurrency/restaurant2" arguments='5' />
<jrun cls="concurrency.waxomatic.WaxOMatic" dirpath="../concurrency/waxomatic" />
<jrun cls="concurrency.waxomatic2.WaxOMatic2" dirpath="../concurrency/waxomatic2" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AssociativeArray" />
<jrun cls="Bits" />
<jrun cls="CanonicalMapping" />
@ -44,7 +43,6 @@
<jrun cls="TypesForSets" />
<jrun cls="Unsupported" />
<jrun cls="Utilities" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="BreakAndContinue" />
<jrun cls="CommaOperator" />
<jrun cls="ForEachFloat" />
@ -20,7 +19,6 @@
<jrun cls="StringSwitch" />
<jrun cls="VowelsAndConsonants" />
<jrun cls="WhileTest" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,9 +6,7 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="SimpleDebugging" failOnError='false' msg='* Exception was Expected *' />
<delete file="failures"/>
</target>
</project>

View File

@ -11,13 +11,11 @@ public class EnumMaps {
public static void main(String[] args) {
EnumMap<AlarmPoints,Command> 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<AlarmPoints,Command> e : em.entrySet()) {
printnb(e.getKey() + ": ");

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="BigEnumSet" />
<jrun cls="enumerated.Burrito" dirpath="../enumerated" />
<jrun cls="CarWash" />
@ -34,7 +33,6 @@
<jrun cls="enumerated.menu.Meal" dirpath="../enumerated/menu" />
<jrun cls="enumerated.menu.Meal2" dirpath="../enumerated/menu" />
<jrun cls="enumerated.menu.TypeOfFood" dirpath="../enumerated/menu" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AlwaysFinally" />
<jrun cls="Cleanup" />
<jrun cls="CleanupIdiom" />
@ -31,7 +30,6 @@
<jrun cls="TurnOffChecking" />
<jrun cls="WhoCalled" />
<jrun cls="WithFinally" />
<delete file="failures"/>
</target>
</project>

View File

@ -11,10 +11,7 @@ class Customer {
public String toString() { return "Customer " + id; }
// A method to produce Generator objects:
public static Generator<Customer> generator() {
return new Generator<Customer>() {
@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<Teller> generator =
new Generator<Teller>() {
@Override
public Teller next() { return new Teller(); }
};
() -> new Teller();
}
public class BankTeller {

View File

@ -15,7 +15,7 @@ class Foo2<T> {
class IntegerFactory implements FactoryI<Integer> {
@Override
public Integer create() {
return new Integer(0);
return 0;
}
}

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="ApplyTest" />
<jrun cls="ArrayMaker" />
<jrun cls="ArrayOfGeneric" />
@ -78,7 +77,6 @@
<jrun cls="Wildcards" />
<jrun cls="generics.coffee.CoffeeGenerator" dirpath="../generics/coffee" />
<jrun cls="generics.decorator.Decoration" dirpath="../generics/decorator" />
<delete file="failures"/>
</target>
</project>

View File

@ -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);

View File

@ -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));

View File

@ -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);

View File

@ -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);
}

View File

@ -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);

View File

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

View File

@ -25,31 +25,21 @@ InterruptableLongRunningCallable extends JFrame {
private TaskManager<String,CallableTask> 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<String,CallableTask> 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<String,CallableTask> tt : manager)
tt.task.id(); // No cast required
for(String result : manager.getResults())
System.out.println(result);
});
setLayout(new FlowLayout());
add(b1);

View File

@ -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);

View File

@ -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());

View File

@ -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);

View File

@ -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);
}

View File

@ -27,13 +27,9 @@ class MonitoredCallable implements Callable<String> {
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<String,MonitoredCallable> 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);

View File

@ -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);

View File

@ -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) {

View File

@ -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);

View File

@ -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"),

View File

@ -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!");
});
}
} ///:~

View File

@ -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!");
});
}
} ///:~

View File

@ -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);

View File

@ -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));

View File

@ -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);

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="BorderLayout1" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="Borders" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="Button1" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
@ -47,7 +46,6 @@
<jrun cls="TextPane" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="TicTacToe" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="TrackEvent" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<delete file="failures"/>
</target>
</project>

View File

@ -6,20 +6,15 @@ import java.util.*;
class ReversibleArrayList<T> extends ArrayList<T> {
public ReversibleArrayList(Collection<T> c) { super(c); }
public Iterable<T> reversed() {
return new Iterable<T>() {
return () -> new Iterator<T>() {
int current = size() - 1;
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
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();
}
};
}

View File

@ -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());

View File

@ -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) *///:~

View File

@ -4,32 +4,24 @@ import java.util.*;
public class MultiIterableClass extends IterableClass {
public Iterable<String> reversed() {
return new Iterable<String>() {
return () -> new Iterator<String>() {
int current = words.length - 1;
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
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<String> randomized() {
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
List<String> shuffled =
new ArrayList<>(Arrays.asList(words));
Collections.shuffle(shuffled, new Random(47));
return shuffled.iterator();
}
return () -> {
List<String> shuffled =
new ArrayList<>(Arrays.asList(words));
Collections.shuffle(shuffled, new Random(47));
return shuffled.iterator();
};
}
public static void main(String[] args) {

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AdapterMethodIdiom" />
<jrun cls="AddingGroups" />
<jrun cls="ApplesAndOrangesWithGenerics" />
@ -42,7 +41,6 @@
<jrun cls="Statistics" />
<jrun cls="UniqueWords" />
<jrun cls="UniqueWordsAlphabetic" />
<delete file="failures"/>
</target>
</project>

View File

@ -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));

View File

@ -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

View File

@ -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());

View File

@ -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()});
}

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="ArrayClassObj" />
<jrun cls="ArrayInit" />
<jrun cls="ArrayNew" />
@ -40,7 +39,6 @@
<jrun cls="TerminationCondition" />
<jrun cls="VarArgs" />
<jrun cls="VarargType" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AnonymousConstructor" />
<jrun cls="BigEgg" />
<jrun cls="BigEgg2" />
@ -36,7 +35,6 @@
<jrun cls="Sequence" />
<jrun cls="TestBed$Tester" />
<jrun cls="TestParcel" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AdaptedRandomDoubles" />
<jrun cls="Adventure" />
<jrun cls="Factories" />
@ -21,7 +20,6 @@
<jrun cls="interfaces.music4.Music4" dirpath="../interfaces/music4" />
<jrun cls="interfaces.music5.Music5" dirpath="../interfaces/music5" />
<jrun cls="interfaces.nesting.NestingInterfaces" dirpath="../interfaces/nesting" />
<delete file="failures"/>
</target>
</project>

View File

@ -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));
}

View File

@ -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"));

View File

@ -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"));

View File

@ -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)

View File

@ -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

View File

@ -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));
}

View File

@ -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(

View File

@ -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(

View File

@ -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));
}
}
}
};

View File

@ -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);
}
} ///:~

View File

@ -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")));

View File

@ -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 {

View File

@ -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();

View File

@ -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:

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AStoreCADState" />
<jrun cls="AvailableCharSets" />
<jrun cls="BasicFileOutput" />
@ -51,7 +50,6 @@
<jrun cls="Worm" />
<jrun cls="ZipCompress" arguments='ZipCompress.java' />
<jrun cls="ThawAlien" failOnError='false' msg='* Exception was Expected *' />
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="ConfigureLogging" />
<jrun cls="CustomHandler" />
<jrun cls="InfoLogging" />
@ -19,7 +18,6 @@
<jrun cls="MultipleHandlers2" />
<jrun cls="PrintableLogRecord" />
<jrun cls="SimpleFilter" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,9 +6,8 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="net.mindview.atunit.AtUnit" dirpath="../net/mindview/atunit" />
<jrun cls="net.mindview.atunit.AtUnitRemover" dirpath="../net/mindview/atunit" arguments='..' />
<jrun cls="net.mindview.atunit.AtUnitRemover" dirpath="../net/mindview/atunit" arguments='..' failOnError='false' msg='* Exception was Expected *' />
<jrun cls="net.mindview.atunit.ClassNameFinder" dirpath="../net/mindview/atunit" />
<jrun cls="net.mindview.util.ContainerMethodDifferences" dirpath="../net/mindview/util" />
<jrun cls="net.mindview.util.CountingIntegerList" dirpath="../net/mindview/util" />
@ -19,7 +18,6 @@
<jrun cls="net.mindview.util.New" dirpath="../net/mindview/util" />
<jrun cls="net.mindview.util.ProcessFiles" dirpath="../net/mindview/util" />
<jrun cls="net.mindview.util.TextFile" dirpath="../net/mindview/util" />
<delete file="failures"/>
</target>
</project>

View File

@ -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

View File

@ -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[]

View File

@ -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) *///:~

View File

@ -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

View File

@ -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);
});
}
} ///:~

View File

@ -10,16 +10,13 @@ public class TextFile extends ArrayList<String> {
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<String> {
// 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<String> {
}
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);

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="ChatterClient" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="ChatterServer" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="MultiSimpleClient" failOnError='false' msg='* Exception was Expected *' />
@ -14,7 +13,6 @@
<jrun cls="SimpleClient" failOnError='false' msg='* Exception was Expected *' />
<jrun cls="SimpleServer" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
<jrun cls="WhoAmI" arguments='MindviewToshibaLaptop' />
<delete file="failures"/>
</target>
</project>

View File

@ -6,10 +6,8 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="HelloDate" />
<jrun cls="ShowProperties" />
<delete file="failures"/>
</target>
</project>

View File

@ -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:

View File

@ -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);
}

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="Assignment" />
<jrun cls="AutoInc" />
<jrun cls="BitManipulation" />
@ -28,7 +27,6 @@
<jrun cls="StringOperators" />
<jrun cls="TernaryIfElse" />
<jrun cls="URShift" />
<delete file="failures"/>
</target>
</project>

View File

@ -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;

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="CommandPattern" />
<jrun cls="Facade" />
<jrun cls="PaperScissorsRock" />
@ -30,7 +29,6 @@
<jrun cls="patterns.trashvisitor.TrashVisitor" dirpath="../patterns/trashvisitor" />
<jrun cls="patterns.visitor.BeeAndFlowers" dirpath="../patterns/visitor" />
<jrun cls="patterns.visualobserver.BoxObserver" dirpath="../patterns/visualobserver" failOnError='false' timeOut='4000' />
<delete file="failures"/>
</target>
</project>

View File

@ -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;
}
} ///:~

View File

@ -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;
}
} ///:~

View File

@ -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;
}
} ///:~

View File

@ -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;
}
} ///:~

View File

@ -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);
}

View File

@ -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;

View File

@ -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) {

View File

@ -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();

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="CovariantReturn" />
<jrun cls="FieldAccess" />
<jrun cls="polymorphism.Frog" dirpath="../polymorphism" />
@ -21,7 +20,6 @@
<jrun cls="polymorphism.music.Music" dirpath="../polymorphism/music" />
<jrun cls="polymorphism.music.Music2" dirpath="../polymorphism/music" />
<jrun cls="polymorphism.music3.Music3" dirpath="../polymorphism/music3" />
<delete file="failures"/>
</target>
</project>

View File

@ -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);
}
}
} ///:~

View File

@ -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()));

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="AddingClone" />
<jrun cls="Alias1" />
<jrun cls="Alias2" />
@ -25,7 +24,6 @@
<jrun cls="PassReferences" />
<jrun cls="Snake" />
<jrun cls="Stringer" />
<delete file="failures"/>
</target>
</project>

View File

@ -6,8 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<delete file="failures"/>
</target>
</project>

View File

@ -6,7 +6,6 @@
<import file="../Ant-Common.xml"/>
<target name="run" description="Compile and run" depends="build">
<touch file="failures"/>
<jrun cls="Bath" />
<jrun cls="Beetle" />
<jrun cls="BlankFinal" />
@ -26,7 +25,6 @@
<jrun cls="SpaceShipDelegation" />
<jrun cls="SprinklerSystem" />
<jrun cls="Wind" />
<delete file="failures"/>
</target>
</project>

Some files were not shown because too many files have changed in this diff Show More