After "Arrays" chapter completed

This commit is contained in:
Bruce Eckel 2016-01-25 18:05:55 -08:00
parent de9c3fb025
commit 4f6362334d
689 changed files with 4450 additions and 3060 deletions

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Creating non-embedded tests. // Creating non-embedded tests
package annotations; package annotations;
import onjava.atunit.*; import onjava.atunit.*;
import onjava.*; import onjava.*;
@ -16,7 +16,8 @@ public class AtUnitComposition {
@Test boolean _methodTwo() { @Test boolean _methodTwo() {
return testObject.methodTwo() == 2; return testObject.methodTwo() == 2;
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitComposition.class"); "onjava.atunit.AtUnit AtUnitComposition.class");
} }

View File

@ -22,7 +22,8 @@ public class AtUnitExample1 {
// Shows output for failure: // Shows output for failure:
@Test boolean failureTest() { return false; } @Test boolean failureTest() { return false; }
@Test boolean anotherDisappointment() { return false; } @Test boolean anotherDisappointment() { return false; }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExample1.class"); "onjava.atunit.AtUnit AtUnitExample1.class");
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Assertions and exceptions can be used in @Tests. // Assertions and exceptions can be used in @Tests
package annotations; package annotations;
import java.io.*; import java.io.*;
import onjava.atunit.*; import onjava.atunit.*;
@ -30,7 +30,8 @@ public class AtUnitExample2 {
assert methodTwo() == 2: "methodTwo must equal 2"; assert methodTwo() == 2: "methodTwo must equal 2";
return methodOne().equals("This is methodOne"); return methodOne().equals("This is methodOne");
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExample2.class"); "onjava.atunit.AtUnit AtUnitExample2.class");
} }

View File

@ -25,7 +25,8 @@ public class AtUnitExample3 {
return methodOne().equals("This is methodOne"); return methodOne().equals("This is methodOne");
} }
@Test boolean m2() { return methodTwo() == 2; } @Test boolean m2() { return methodTwo() == 2; }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExample3.class"); "onjava.atunit.AtUnit AtUnitExample3.class");
} }

View File

@ -16,10 +16,8 @@ public class AtUnitExample4 {
public AtUnitExample4(String word) { this.word = word; } public AtUnitExample4(String word) { this.word = word; }
public String getWord() { return word; } public String getWord() { return word; }
public String scrambleWord() { public String scrambleWord() {
// <* Improve this: *> List<Character> chars =
List<Character> chars = new ArrayList<>(); Arrays.asList(ConvertTo.boxed(word.toCharArray()));
for(Character c : word.toCharArray())
chars.add(c);
Collections.shuffle(chars, rand); Collections.shuffle(chars, rand);
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for(char ch : chars) for(char ch : chars)
@ -41,7 +39,7 @@ public class AtUnitExample4 {
return getWord().equals("are"); return getWord().equals("are");
} }
@Test boolean scramble1() { @Test boolean scramble1() {
// Change to a specific seed to get verifiable results: // Change to specific seed to get verifiable results:
rand = new Random(47); rand = new Random(47);
System.out.println("'" + getWord() + "'"); System.out.println("'" + getWord() + "'");
String scrambled = scrambleWord(); String scrambled = scrambleWord();
@ -55,7 +53,8 @@ public class AtUnitExample4 {
System.out.println(scrambled); System.out.println(scrambled);
return scrambled.equals("tsaeborornussu"); return scrambled.equals("tsaeborornussu");
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
System.out.println("starting"); System.out.println("starting");
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExample4.class"); "onjava.atunit.AtUnit AtUnitExample4.class");
@ -64,17 +63,13 @@ public class AtUnitExample4 {
/* Output: /* Output:
starting starting
annotations.AtUnitExample4 annotations.AtUnitExample4
. words 'All' . scramble1 'All'
(failed) lAl
. scramble2 'brontosauruses' . scramble2 'brontosauruses'
tsaeborornussu tsaeborornussu
. scramble1 'are' . words 'are'
rae
(failed)
(3 tests)
>>> 2 FAILURES <<< OK (3 tests)
annotations.AtUnitExample4: words
annotations.AtUnitExample4: scramble1
*/ */

View File

@ -40,7 +40,8 @@ public class AtUnitExample5 {
output.print("test3"); output.print("test3");
return true; return true;
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExample5.class"); "onjava.atunit.AtUnit AtUnitExample5.class");
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Creating non-embedded tests. // Creating non-embedded tests
package annotations; package annotations;
import onjava.atunit.*; import onjava.atunit.*;
import onjava.*; import onjava.*;
@ -12,7 +12,8 @@ public class AtUnitExternalTest extends AtUnitExample1 {
return methodOne().equals("This is methodOne"); return methodOne().equals("This is methodOne");
} }
@Test boolean _methodTwo() { return methodTwo() == 2; } @Test boolean _methodTwo() { return methodTwo() == 2; }
public static void main(String[] args) throws Exception{ public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit AtUnitExternalTest.class"); "onjava.atunit.AtUnit AtUnitExternalTest.class");
} }

View File

@ -21,7 +21,8 @@ public class HashSetTest {
testObject.remove("one"); testObject.remove("one");
assert testObject.isEmpty(); assert testObject.isEmpty();
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit HashSetTest.class"); "onjava.atunit.AtUnit HashSetTest.class");
} }

View File

@ -7,17 +7,17 @@ import java.util.*;
public class PasswordUtils { public class PasswordUtils {
@UseCase(id = 47, description = @UseCase(id = 47, description =
"Passwords must contain at least one numeric") "Passwords must contain at least one numeric")
public boolean validatePassword(String password) { public boolean validatePassword(String passwd) {
return (password.matches("\\w*\\d\\w*")); return (passwd.matches("\\w*\\d\\w*"));
} }
@UseCase(id = 48) @UseCase(id = 48)
public String encryptPassword(String password) { public String encryptPassword(String passwd) {
return new StringBuilder(password).reverse().toString(); return new StringBuilder(passwd).reverse().toString();
} }
@UseCase(id = 49, description = @UseCase(id = 49, description =
"New passwords can't equal previously used ones") "New passwords can't equal previously used ones")
public boolean checkForNewPassword( public boolean checkForNewPassword(
List<String> prevPasswords, String password) { List<String> prevPasswords, String passwd) {
return !prevPasswords.contains(password); return !prevPasswords.contains(passwd);
} }
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// A stack built on a linkedList. // A stack built on a linkedList
package annotations; package annotations;
import java.util.*; import java.util.*;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Applying @Unit to generics. // Applying @Unit to generics
package annotations; package annotations;
import onjava.atunit.*; import onjava.atunit.*;
import onjava.*; import onjava.*;
@ -26,7 +26,8 @@ public class StackLStringTest extends StackL<String> {
assert top().equals("B"); assert top().equals("B");
assert top().equals("B"); assert top().equals("B");
} }
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
OSExecute.command("java -cp .. " + OSExecute.command("java -cp .. " +
"onjava.atunit.AtUnit StackLStringTest.class"); "onjava.atunit.AtUnit StackLStringTest.class");
} }

View File

@ -17,7 +17,8 @@ public class UseCaseTracker {
} }
} }
for(int i : useCases) { for(int i : useCases) {
System.out.println("Warning: Missing use case-" + i); System.out.println(
"Warning: Missing use case-" + i);
} }
} }
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Reflection-based annotation processor. // Reflection-based annotation processor
// {Args: annotations.database.Member} // {Args: annotations.database.Member}
package annotations.database; package annotations.database;
import java.lang.annotation.*; import java.lang.annotation.*;
@ -10,7 +10,8 @@ import java.lang.reflect.*;
import java.util.*; import java.util.*;
public class TableCreator { public class TableCreator {
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
if(args.length < 1) { if(args.length < 1) {
System.out.println("arguments: annotated classes"); System.out.println("arguments: annotated classes");
System.exit(0); System.exit(0);
@ -30,7 +31,8 @@ public class TableCreator {
List<String> columnDefs = new ArrayList<>(); List<String> columnDefs = new ArrayList<>();
for(Field field : cl.getDeclaredFields()) { for(Field field : cl.getDeclaredFields()) {
String columnName = null; String columnName = null;
Annotation[] anns = field.getDeclaredAnnotations(); Annotation[] anns =
field.getDeclaredAnnotations();
if(anns.length < 1) if(anns.length < 1)
continue; // Not a db table column continue; // Not a db table column
if(anns[0] instanceof SQLInteger) { if(anns[0] instanceof SQLInteger) {
@ -57,7 +59,8 @@ public class TableCreator {
StringBuilder createCommand = new StringBuilder( StringBuilder createCommand = new StringBuilder(
"CREATE TABLE " + tableName + "("); "CREATE TABLE " + tableName + "(");
for(String columnDef : columnDefs) for(String columnDef : columnDefs)
createCommand.append("\n " + columnDef + ","); createCommand.append(
"\n " + columnDef + ",");
// Remove trailing comma // Remove trailing comma
String tableCreate = createCommand.substring( String tableCreate = createCommand.substring(
0, createCommand.length() - 1) + ");"; 0, createCommand.length() - 1) + ");";

View File

@ -7,5 +7,5 @@ package annotations.database;
public @interface Uniqueness { public @interface Uniqueness {
Constraints constraints() Constraints constraints()
default @Constraints(unique=true); default @Constraints(unique = true);
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// javac-based annotation processing. // javac-based annotation processing
package annotations.ifx; package annotations.ifx;
import java.lang.annotation.*; import java.lang.annotation.*;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// javac-based annotation processing. // javac-based annotation processing
package annotations.ifx; package annotations.ifx;
import javax.annotation.processing.*; import javax.annotation.processing.*;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;
@ -51,8 +51,8 @@ extends AbstractProcessor {
private void private void
writeInterfaceFile(String interfaceName) { writeInterfaceFile(String interfaceName) {
try(Writer writer = processingEnv.getFiler() try(Writer writer = processingEnv.getFiler()
.createSourceFile(interfaceName) .createSourceFile(interfaceName)
.openWriter()) { .openWriter()) {
String packageName = elementUtils String packageName = elementUtils
.getPackageOf(interfaceMethods .getPackageOf(interfaceMethods
.get(0)).toString(); .get(0)).toString();

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// javac-based annotation processing. // javac-based annotation processing
package annotations.ifx; package annotations.ifx;
@ExtractInterface(interfaceName="IMultiplier") @ExtractInterface(interfaceName="IMultiplier")

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// A bare-bones annotation. // A bare-bones annotation
package annotations.simplest; package annotations.simplest;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// A bare-bones annotation processor. // A bare-bones annotation processor
package annotations.simplest; package annotations.simplest;
import javax.annotation.processing.*; import javax.annotation.processing.*;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;

View File

@ -2,19 +2,20 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Searching with a Comparator. // Searching with a Comparator
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
public class AlphabeticSearch { public class AlphabeticSearch {
public static void main(String[] args) { public static void main(String[] args) {
String[] sa = Generated.array(new String[30], String[] sa = new Rand.String().array(30);
new RandomSupplier.String(5));
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER); Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(sa)); show(sa);
int index = Arrays.binarySearch(sa, sa[10], int index = Arrays.binarySearch(sa, sa[10],
String.CASE_INSENSITIVE_ORDER); String.CASE_INSENSITIVE_ORDER);
System.out.println("Index: "+ index + "\n"+ sa[index]); System.out.println(
"Index: "+ index + "\n"+ sa[index]);
} }
} }
/* Output: /* Output:

81
arrays/ArrayCopying.java Normal file
View File

@ -0,0 +1,81 @@
// arrays/ArrayCopying.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstrate Arrays.copy() and Arrays.copyOf()
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
class Sup { // Superclass
private int id;
public Sup(int n) { id = n; }
@Override
public String toString() {
return getClass().getSimpleName() + id;
}
}
class Sub extends Sup { // Subclass
public Sub(int n) { super(n); }
}
public class ArrayCopying {
public static final int SZ = 15;
public static void main(String[] args) {
int[] a1 = new int[SZ];
Arrays.setAll(a1, new Count.Integer()::get);
show("a1", a1);
int[] a2 = Arrays.copyOf(a1, a1.length); // (1)
// Prove they are distinct arrays:
Arrays.fill(a1, 1);
show("a1", a1);
show("a2", a2);
// Create a shorter result:
a2 = Arrays.copyOf(a2, a2.length/2); // (2)
show("a2", a2);
// Allocate more space:
a2 = Arrays.copyOf(a2, a2.length + 5);
show("a2", a2);
// Also copies wrapped arrays:
Integer[] a3 = new Integer[SZ]; // (3)
Arrays.setAll(a3, new Count.Integer()::get);
Integer[] a4 = Arrays.copyOfRange(a3, 4, 12);
show("a4", a4);
Sub[] d = new Sub[SZ/2];
Arrays.setAll(d, Sub::new);
// Produce Sup[] from Sub[]:
Sup[] b =
Arrays.copyOf(d, d.length, Sup[].class); // (4)
show(b);
// This "downcast" works fine:
Sub[] d2 =
Arrays.copyOf(b, b.length, Sub[].class); // (5)
show(d2);
// Bad "downcast" compiles but throws exception:
Sup[] b2 = new Sup[SZ/2];
Arrays.setAll(b2, Sup::new);
try {
Sub[] d3 =
Arrays.copyOf(b2, b2.length, Sub[].class); // (6)
} catch(Exception e) {
System.out.println(e);
}
}
}
/* Output:
a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
a1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
a2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
a2 = [0, 1, 2, 3, 4, 5, 6]
a2 = [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0]
a4 = [4, 5, 6, 7, 8, 9, 10, 11]
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
java.lang.ArrayStoreException
*/

View File

@ -2,15 +2,15 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Arrays of generic types won't compile.
public class ArrayOfGenericType<T> { public class ArrayOfGenericType<T> {
T[] array; // OK T[] array; // OK
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public ArrayOfGenericType(int size) { public ArrayOfGenericType(int size) {
//- array = new T[size]; // Illegal // error: generic array creation:
array = (T[])new Object[size]; // "unchecked" Warning // - array = new T[size];
array = (T[])new Object[size]; // unchecked cast
} }
// Illegal: // error: generic array creation:
//- public <U> U[] makeArray() { return new U[10]; } //- public <U> U[] makeArray() { return new U[10]; }
} }

View File

@ -2,7 +2,6 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// It is possible to create arrays of generics.
import java.util.*; import java.util.*;
public class ArrayOfGenerics { public class ArrayOfGenerics {
@ -10,10 +9,14 @@ public class ArrayOfGenerics {
public static void main(String[] args) { public static void main(String[] args) {
List<String>[] ls; List<String>[] ls;
List[] la = new List[10]; List[] la = new List[10];
ls = (List<String>[])la; // "Unchecked" warning ls = (List<String>[])la; // Unchecked cast
ls[0] = new ArrayList<>(); ls[0] = new ArrayList<>();
// Compile-time checking produces an error:
//- ls[1] = new ArrayList<Integer>(); // -ls[1] = new ArrayList<Integer>();
// error: incompatible types: ArrayList<Integer>
// cannot be converted to List<String>
// ls[1] = new ArrayList<Integer>();
// ^
// The problem: List<String> is a subtype of Object // The problem: List<String> is a subtype of Object
Object[] objects = ls; // So assignment is OK Object[] objects = ls; // So assignment is OK
@ -22,10 +25,9 @@ public class ArrayOfGenerics {
// However, if your needs are straightforward it is // However, if your needs are straightforward it is
// possible to create an array of generics, albeit // possible to create an array of generics, albeit
// with an "unchecked" warning: // with an "unchecked cast" warning:
List<BerylliumSphere>[] spheres = List<BerylliumSphere>[] spheres =
(List<BerylliumSphere>[])new List[10]; (List<BerylliumSphere>[])new List[10];
for(int i = 0; i < spheres.length; i++) Arrays.setAll(spheres, n -> new ArrayList<>());
spheres[i] = new ArrayList<>();
} }
} }

View File

@ -2,8 +2,9 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Initialization & re-assignment of arrays. // Initialization & re-assignment of arrays
import java.util.*; import java.util.*;
import static onjava.ArrayShow.*;
public class ArrayOptions { public class ArrayOptions {
public static void main(String[] args) { public static void main(String[] args) {
@ -13,23 +14,25 @@ public class ArrayOptions {
// The references inside the array are // The references inside the array are
// automatically initialized to null: // automatically initialized to null:
System.out.println("b: " + Arrays.toString(b)); show("b", b);
BerylliumSphere[] c = new BerylliumSphere[4]; BerylliumSphere[] c = new BerylliumSphere[4];
for(int i = 0; i < c.length; i++) for(int i = 0; i < c.length; i++)
if(c[i] == null) // Can test for null reference if(c[i] == null) // Can test for null reference
c[i] = new BerylliumSphere(); c[i] = new BerylliumSphere();
// Aggregate initialization: // Aggregate initialization:
BerylliumSphere[] d = { new BerylliumSphere(), BerylliumSphere[] d = {
new BerylliumSphere(), new BerylliumSphere() new BerylliumSphere(),
new BerylliumSphere(),
new BerylliumSphere()
}; };
// Dynamic aggregate initialization: // Dynamic aggregate initialization:
a = new BerylliumSphere[]{ a = new BerylliumSphere[]{
new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere(),
}; };
// (Trailing comma is optional)
// (Trailing comma is optional in both cases)
System.out.println("a.length = " + a.length); System.out.println("a.length = " + a.length);
System.out.println("b.length = " + b.length); System.out.println("b.length = " + b.length);
System.out.println("c.length = " + c.length); System.out.println("c.length = " + c.length);
@ -43,14 +46,14 @@ public class ArrayOptions {
// The primitives inside the array are // The primitives inside the array are
// automatically initialized to zero: // automatically initialized to zero:
System.out.println("f: " + Arrays.toString(f)); show("f", f);
int[] g = new int[4]; int[] g = new int[4];
for(int i = 0; i < g.length; i++) for(int i = 0; i < g.length; i++)
g[i] = i*i; g[i] = i*i;
int[] h = { 11, 47, 93 }; int[] h = { 11, 47, 93 };
// Compile error: variable e not initialized: // Compile error: variable e not initialized:
//- print("e.length = " + e.length); //- System.out.println("e.length = " + e.length);
System.out.println("f.length = " + f.length); System.out.println("f.length = " + f.length);
System.out.println("g.length = " + g.length); System.out.println("g.length = " + g.length);
System.out.println("h.length = " + h.length); System.out.println("h.length = " + h.length);

View File

@ -2,35 +2,32 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using Arrays.binarySearch(). // Using Arrays.binarySearch()
import java.util.*; import java.util.*;
import java.util.function.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
public class ArraySearching { public class ArraySearching {
public static void main(String[] args) { public static void main(String[] args) {
Supplier<Integer> gen = Rand.int_ rand = new Rand.int_();
new RandomSupplier.Integer(1000); int[] a = new Rand.int_().array(25);
int[] a = ConvertTo.primitive(
Generated.array(new Integer[25], gen));
Arrays.sort(a); Arrays.sort(a);
System.out.println( show("Sorted array", a);
"Sorted array: " + Arrays.toString(a));
while(true) { while(true) {
int r = gen.get(); int r = rand.getAsInt();
int location = Arrays.binarySearch(a, r); int location = Arrays.binarySearch(a, r);
if(location >= 0) { if(location >= 0) {
System.out.println( System.out.println(
"Location of " + r + " is " + location + "Location of " + r + " is " + location +
", a[" + location + "] = " + a[location]); ", a[" + location + "] is " + a[location]);
break; // Out of while loop break; // Out of while loop
} }
} }
} }
} }
/* Output: /* Output:
Sorted array: [128, 140, 200, 207, 258, 258, 278, 288, 322, Sorted array: [125, 267, 635, 650, 1131, 1506, 1634,
429, 511, 520, 522, 551, 555, 589, 693, 704, 809, 861, 861, 2400, 2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070,
868, 916, 961, 998] 5682, 5807, 6177, 6193, 6656, 7021, 8479, 8737, 9954]
Location of 322 is 8, a[8] = 322 Location of 635 is 2, a[2] is 635
*/ */

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Creating multidimensional arrays. // Creating multidimensional arrays
import java.util.*; import java.util.*;
public class AssemblingMultidimensionalArrays { public class AssemblingMultidimensionalArrays {

View File

@ -0,0 +1,21 @@
// arrays/BadMicroBenchmark.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import static onjava.TimeIt.*;
public class BadMicroBenchmark {
static final int SIZE = 20_000_000;
public static void main(String[] args) {
long[] la = new long[SIZE];
System.out.print("setAll: ");
timeIt(() -> Arrays.setAll(la, n -> n));
System.out.print("parallelSetAll: ");
timeIt(() -> Arrays.parallelSetAll(la, n -> n));
}
}
/* Output:
setAll: 27
parallelSetAll: 53
*/

View File

@ -0,0 +1,22 @@
// arrays/BadMicroBenchmark2.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Reversing the test order
import java.util.*;
import static onjava.TimeIt.*;
public class BadMicroBenchmark2 {
static final int SIZE = 20_000_000;
public static void main(String[] args) {
long[] la = new long[SIZE];
System.out.print("parallelSetAll: ");
timeIt(() -> Arrays.parallelSetAll(la, n -> n));
System.out.print("setAll: ");
timeIt(() -> Arrays.setAll(la, n -> n));
}
}
/* Output:
parallelSetAll: 38
setAll: 63
*/

View File

@ -0,0 +1,34 @@
// arrays/BadMicroBenchmark3.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Relying on a common resource
import java.util.*;
import static onjava.TimeIt.*;
public class BadMicroBenchmark3 {
static final int SIZE = 20_000_000;
public static void main(String[] args) {
long[] la = new long[SIZE];
Random r = new Random();
System.out.print("parallelSetAll: ");
timeIt(() ->
Arrays.parallelSetAll(la, n -> r.nextLong()));
System.out.print("setAll: ");
timeIt(() ->
Arrays.setAll(la, n -> r.nextLong()));
SplittableRandom sr = new SplittableRandom();
System.out.print("parallelSetAll: ");
timeIt(() ->
Arrays.parallelSetAll(la, n -> sr.nextLong()));
System.out.print("setAll: ");
timeIt(() ->
Arrays.setAll(la, n -> sr.nextLong()));
}
}
/* Output:
parallelSetAll: 5150
setAll: 649
parallelSetAll: 277
setAll: 246
*/

View File

@ -3,6 +3,8 @@
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*; import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
class BerylliumSphere { class BerylliumSphere {
private static long counter; private static long counter;
@ -16,17 +18,16 @@ public class CollectionComparison {
BerylliumSphere[] spheres = new BerylliumSphere[10]; BerylliumSphere[] spheres = new BerylliumSphere[10];
for(int i = 0; i < 5; i++) for(int i = 0; i < 5; i++)
spheres[i] = new BerylliumSphere(); spheres[i] = new BerylliumSphere();
System.out.println(Arrays.toString(spheres)); show(spheres);
System.out.println(spheres[4]); System.out.println(spheres[4]);
List<BerylliumSphere> sphereList= new ArrayList<>(); List<BerylliumSphere> sphereList = Suppliers.create(
for(int i = 0; i < 5; i++) ArrayList::new, BerylliumSphere::new, 5);
sphereList.add(new BerylliumSphere());
System.out.println(sphereList); System.out.println(sphereList);
System.out.println(sphereList.get(4)); System.out.println(sphereList.get(4));
int[] integers = { 0, 1, 2, 3, 4, 5 }; int[] integers = { 0, 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(integers)); show(integers);
System.out.println(integers[4]); System.out.println(integers[4]);
List<Integer> intList = new ArrayList<>( List<Integer> intList = new ArrayList<>(

View File

@ -2,10 +2,11 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Implementing Comparable in a class. // Implementing Comparable in a class
import java.util.*; import java.util.*;
import java.util.function.*; import java.util.function.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
public class CompType implements Comparable<CompType> { public class CompType implements Comparable<CompType> {
int i; int i;
@ -26,19 +27,17 @@ public class CompType implements Comparable<CompType> {
public int compareTo(CompType rv) { public int compareTo(CompType rv) {
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1)); return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
} }
private static Random r = new Random(47); private static SplittableRandom r =
public static Supplier<CompType> generator() { new SplittableRandom(47);
return () -> public static CompType get() {
new CompType(r.nextInt(100), r.nextInt(100)); return new CompType(r.nextInt(100), r.nextInt(100));
} }
public static void main(String[] args) { public static void main(String[] args) {
CompType[] a = CompType[] a = new CompType[12];
Generated.array(new CompType[12], generator()); Arrays.setAll(a, n -> get());
System.out.println("before sorting:"); show("Before sorting", a);
System.out.println(Arrays.toString(a));
Arrays.sort(a); Arrays.sort(a);
System.out.println("after sorting:"); show("After sorting", a);
System.out.println(Arrays.toString(a));
} }
} }
/* Output: /* Output:

View File

@ -2,9 +2,10 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Implementing a Comparator for a class. // Implementing a Comparator for a class
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
class CompTypeComparator implements Comparator<CompType> { class CompTypeComparator implements Comparator<CompType> {
public int compare(CompType o1, CompType o2) { public int compare(CompType o1, CompType o2) {
@ -14,13 +15,11 @@ class CompTypeComparator implements Comparator<CompType> {
public class ComparatorTest { public class ComparatorTest {
public static void main(String[] args) { public static void main(String[] args) {
CompType[] a = Generated.array( CompType[] a = new CompType[12];
new CompType[12], CompType.generator()); Arrays.setAll(a, n -> CompType.get());
System.out.println("before sorting:"); show("Before sorting", a);
System.out.println(Arrays.toString(a));
Arrays.sort(a, new CompTypeComparator()); Arrays.sort(a, new CompTypeComparator());
System.out.println("after sorting:"); show("After sorting", a);
System.out.println(Arrays.toString(a));
} }
} }
/* Output: /* Output:

View File

@ -4,25 +4,57 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using Arrays.equals() // Using Arrays.equals()
import java.util.*; import java.util.*;
import onjava.*;
public class ComparingArrays { public class ComparingArrays {
public static final int SZ = 15;
static String[][] TwoDArray() {
String[][] md = new String[5][];
Arrays.setAll(md, n -> new String[n]);
for(int i = 0; i < md.length; i++)
Arrays.setAll(md[i], new Rand.String()::get);
return md;
}
public static void main(String[] args) { public static void main(String[] args) {
int[] a1 = new int[10]; int[] a1 = new int[SZ], a2 = new int[SZ];
int[] a2 = new int[10]; Arrays.setAll(a1, new Count.Integer()::get);
Arrays.fill(a1, 47); Arrays.setAll(a2, new Count.Integer()::get);
Arrays.fill(a2, 47); System.out.println(
System.out.println(Arrays.equals(a1, a2)); "a1 == a2: " + Arrays.equals(a1, a2));
a2[3] = 11; a2[3] = 11;
System.out.println(Arrays.equals(a1, a2)); System.out.println(
String[] s1 = new String[4]; "a1 == a2: " + Arrays.equals(a1, a2));
Arrays.fill(s1, "Hi");
String[] s2 = { new String("Hi"), new String("Hi"), Integer[] a1w = new Integer[SZ],
new String("Hi"), new String("Hi") }; a2w = new Integer[SZ];
System.out.println(Arrays.equals(s1, s2)); Arrays.setAll(a1w, new Count.Integer()::get);
Arrays.setAll(a2w, new Count.Integer()::get);
System.out.println(
"a1w == a2w: " + Arrays.equals(a1w, a2w));
a2w[3] = 11;
System.out.println(
"a1w == a2w: " + Arrays.equals(a1w, a2w));
String[][] md1 = TwoDArray(), md2 = TwoDArray();
System.out.println(Arrays.deepToString(md1));
System.out.println("deepEquals(md1, md2): " +
Arrays.deepEquals(md1, md2));
System.out.println(
"md1 == md2: " + Arrays.equals(md1, md2));
md1[4][1] = "#$#$#$#";
System.out.println(Arrays.deepToString(md1));
System.out.println("deepEquals(md1, md2): " +
Arrays.deepEquals(md1, md2));
} }
} }
/* Output: /* Output:
true a1 == a2: true
false a1 == a2: false
true a1w == a2w: true
a1w == a2w: false
[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, GcFOWZn, TcQrGse, GZMmJMR]]
deepEquals(md1, md2): true
md1 == md2: false
[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, #$#$#$#, TcQrGse, GZMmJMR]]
deepEquals(md1, md2): false
*/ */

View File

@ -1,45 +0,0 @@
// arrays/CopyingArrays.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using System.arraycopy()
import java.util.*;
public class CopyingArrays {
public static void main(String[] args) {
int[] i = new int[7];
int[] j = new int[10];
Arrays.fill(i, 47);
Arrays.fill(j, 99);
System.out.println("i = " + Arrays.toString(i));
System.out.println("j = " + Arrays.toString(j));
System.arraycopy(i, 0, j, 0, i.length);
System.out.println("j = " + Arrays.toString(j));
int[] k = new int[5];
Arrays.fill(k, 103);
System.arraycopy(i, 0, k, 0, k.length);
System.out.println("k = " + Arrays.toString(k));
Arrays.fill(k, 103);
System.arraycopy(k, 0, i, 0, k.length);
System.out.println("i = " + Arrays.toString(i));
// Objects:
Integer[] u = new Integer[10];
Integer[] v = new Integer[5];
Arrays.fill(u, 47);
Arrays.fill(v, 99);
System.out.println("u = " + Arrays.toString(u));
System.out.println("v = " + Arrays.toString(v));
System.arraycopy(v, 0, u, u.length/2, v.length);
System.out.println("u = " + Arrays.toString(u));
}
}
/* Output:
i = [47, 47, 47, 47, 47, 47, 47]
j = [99, 99, 99, 99, 99, 99, 99, 99, 99, 99]
j = [47, 47, 47, 47, 47, 47, 47, 99, 99, 99]
k = [47, 47, 47, 47, 47]
i = [103, 103, 103, 103, 103, 47, 47]
u = [47, 47, 47, 47, 47, 47, 47, 47, 47, 47]
v = [99, 99, 99, 99, 99]
u = [47, 47, 47, 47, 47, 99, 99, 99, 99, 99]
*/

23
arrays/CountUpward.java Normal file
View File

@ -0,0 +1,23 @@
// arrays/CountUpward.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import java.util.stream.*;
import static onjava.ArrayShow.*;
public class CountUpward {
static long[] fillCounted(int size) {
return LongStream.iterate(0, i -> i + 1)
.limit(size).toArray();
}
public static void main(String[] args) {
long[] l1 = fillCounted(20); // No problem
show(l1);
// On my machine, this runs out of heap space:
//- long[] l2 = fillCounted(10_000_000);
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
*/

View File

@ -4,6 +4,7 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using Arrays.fill() // Using Arrays.fill()
import java.util.*; import java.util.*;
import static onjava.ArrayShow.*;
public class FillingArrays { public class FillingArrays {
public static void main(String[] args) { public static void main(String[] args) {
@ -18,26 +19,26 @@ public class FillingArrays {
double[] a8 = new double[size]; double[] a8 = new double[size];
String[] a9 = new String[size]; String[] a9 = new String[size];
Arrays.fill(a1, true); Arrays.fill(a1, true);
System.out.println("a1 = " + Arrays.toString(a1)); show("a1", a1);
Arrays.fill(a2, (byte)11); Arrays.fill(a2, (byte)11);
System.out.println("a2 = " + Arrays.toString(a2)); show("a2", a2);
Arrays.fill(a3, 'x'); Arrays.fill(a3, 'x');
System.out.println("a3 = " + Arrays.toString(a3)); show("a3", a3);
Arrays.fill(a4, (short)17); Arrays.fill(a4, (short)17);
System.out.println("a4 = " + Arrays.toString(a4)); show("a4", a4);
Arrays.fill(a5, 19); Arrays.fill(a5, 19);
System.out.println("a5 = " + Arrays.toString(a5)); show("a5", a5);
Arrays.fill(a6, 23); Arrays.fill(a6, 23);
System.out.println("a6 = " + Arrays.toString(a6)); show("a6", a6);
Arrays.fill(a7, 29); Arrays.fill(a7, 29);
System.out.println("a7 = " + Arrays.toString(a7)); show("a7", a7);
Arrays.fill(a8, 47); Arrays.fill(a8, 47);
System.out.println("a8 = " + Arrays.toString(a8)); show("a8", a8);
Arrays.fill(a9, "Hello"); Arrays.fill(a9, "Hello");
System.out.println("a9 = " + Arrays.toString(a9)); show("a9", a9);
// Manipulating ranges: // Manipulating ranges:
Arrays.fill(a9, 3, 5, "World"); Arrays.fill(a9, 3, 5, "World");
System.out.println("a9 = " + Arrays.toString(a9)); show("a9", a9);
} }
} }
/* Output: /* Output:

View File

@ -2,11 +2,13 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Returning arrays from methods. // Returning arrays from methods
import java.util.*; import java.util.*;
import static onjava.ArrayShow.*;
public class IceCream { public class IceCream {
private static Random rand = new Random(47); private static SplittableRandom rand =
new SplittableRandom(47);
static final String[] FLAVORS = { static final String[] FLAVORS = {
"Chocolate", "Strawberry", "Vanilla Fudge Swirl", "Chocolate", "Strawberry", "Vanilla Fudge Swirl",
"Mint Chip", "Mocha Almond Fudge", "Rum Raisin", "Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
@ -29,7 +31,7 @@ public class IceCream {
} }
public static void main(String[] args) { public static void main(String[] args) {
for(int i = 0; i < 7; i++) for(int i = 0; i < 7; i++)
System.out.println(Arrays.toString(flavorSet(3))); show(flavorSet(3));
} }
} }
/* Output: /* Output:

View File

@ -0,0 +1,21 @@
// arrays/ModifyExisting.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class ModifyExisting {
public static void main(String[] args) {
double[] da = new double[7];
Arrays.setAll(da, new Rand.Double()::get);
show(da);
Arrays.setAll(da, n -> da[n] / 100); // (1)
show(da);
}
}
/* Output:
[0.73, 0.53, 0.16, 0.19, 0.52, 0.27, 0.26]
[0.0073, 0.0053, 0.0016, 0.0019, 0.0052, 0.0027, 0.0026]
*/

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Multidimensional arrays of "wrapper" objects. // Multidimensional arrays of "wrapper" objects
import java.util.*; import java.util.*;
public class MultiDimWrapperArray { public class MultiDimWrapperArray {

View File

@ -2,7 +2,6 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Creating multidimensional arrays.
import java.util.*; import java.util.*;
public class MultidimensionalPrimitiveArray { public class MultidimensionalPrimitiveArray {

View File

@ -0,0 +1,22 @@
// arrays/ParallelPrefix.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
public class ParallelPrefix {
static final int SIZE = 20_000_000;
public static void main(String[] args) {
long[] nums = new long[SIZE];
Arrays.setAll(nums, n -> n);
Arrays.parallelPrefix(nums, Long::sum);
System.out.println("First 20: " + nums[19]);
System.out.println("First 200: " + nums[199]);
System.out.println("All: " + nums[nums.length-1]);
}
}
/* Output:
First 20: 190
First 200: 19900
All: 199999990000000
*/

View File

@ -0,0 +1,24 @@
// arrays/ParallelSetAll.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
public class ParallelSetAll {
static final int SIZE = 20_000_000;
static void intArray() {
int[] ia = new int[SIZE];
Arrays.setAll(ia, new Rand.int_()::get);
Arrays.parallelSetAll(ia, new Rand.int_()::get);
}
static void longArray() {
long[] la = new long[SIZE];
Arrays.setAll(la, new Rand.long_()::get);
Arrays.parallelSetAll(la, new Rand.long_()::get);
}
public static void main(String[] args) {
intArray();
longArray();
}
}

26
arrays/ParallelSort.java Normal file
View File

@ -0,0 +1,26 @@
// arrays/ParallelSort.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import java.time.*;
import onjava.*;
import static onjava.TimeIt.*;
public class ParallelSort {
static final int SZ = 10_000_000;
public static void main(String[] args) {
int[] ia1 = new Rand.int_().array(SZ);
int[] ia2 = Arrays.copyOf(ia1, ia1.length);
System.out.print("sort(): ");
long millis1 = timeIt(() -> Arrays.sort(ia1));
System.out.print("parallelSort(): ");
long millis2 = timeIt(() -> Arrays.parallelSort(ia2));
System.out.println(millis1/millis2);
}
}
/* Output:
sort(): 484
parallelSort(): 149
3
*/

27
arrays/Prefix1.java Normal file
View File

@ -0,0 +1,27 @@
// arrays/Prefix1.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class Prefix1 {
public static void main(String[] args) {
int[] nums = new Count.int_().array(10);
show(nums);
System.out.println(Arrays.stream(nums)
.reduce(Integer::sum).getAsInt());
Arrays.parallelPrefix(nums, Integer::sum);
show(nums);
System.out.println(Arrays.stream(
new Count.int_().array(6))
.reduce(Integer::sum).getAsInt());
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
45
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
15
*/

20
arrays/Prefix2.java Normal file
View File

@ -0,0 +1,20 @@
// arrays/Prefix2.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class Prefix2 {
public static void main(String[] args) {
String[] strings = new Rand.String(1).array(8);
show(strings);
Arrays.parallelPrefix(strings, (a, b) -> a + b);
show(strings);
}
}
/* Output:
[b, t, p, e, n, p, c, c]
[b, bt, btp, btpe, btpen, btpenp, btpenpc, btpenpcc]
*/

View File

@ -1,23 +0,0 @@
// arrays/PrimitiveConversionDemonstration.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
public class PrimitiveConversionDemonstration {
public static void main(String[] args) {
Integer[] a = Generated.array(Integer.class,
new CountingSupplier.Integer(), 15);
int[] b = ConvertTo.primitive(a);
System.out.println(Arrays.toString(b));
boolean[] c = ConvertTo.primitive(
Generated.array(Boolean.class,
new CountingSupplier.Boolean(), 7));
System.out.println(Arrays.toString(c));
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[true, false, true, false, true, false, true]
*/

View File

@ -24,3 +24,13 @@ class MyList(list): # Inherit from list
list2 = MyList(aList) list2 = MyList(aList)
print(type(list2)) # <class '__main__.MyList'> print(type(list2)) # <class '__main__.MyList'>
print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1] print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1]
output = """
<class 'list'>
[1, 2, 3, 4, 5]
5
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4]
<class '__main__.MyList'>
[8, 7, 6, 5, 4, 3, 2, 1]
"""

View File

@ -5,20 +5,23 @@
import java.util.*; import java.util.*;
public class RaggedArray { public class RaggedArray {
static int val = 1;
public static void main(String[] args) { public static void main(String[] args) {
Random rand = new Random(47); SplittableRandom rand = new SplittableRandom(47);
// 3-D array with varied-length vectors: // 3-D array with varied-length vectors:
int[][][] a = new int[rand.nextInt(7)][][]; int[][][] a = new int[rand.nextInt(7)][][];
for(int i = 0; i < a.length; i++) { for(int i = 0; i < a.length; i++) {
a[i] = new int[rand.nextInt(5)][]; a[i] = new int[rand.nextInt(5)][];
for(int j = 0; j < a[i].length; j++) for(int j = 0; j < a[i].length; j++) {
a[i][j] = new int[rand.nextInt(5)]; a[i][j] = new int[rand.nextInt(5)];
Arrays.setAll(a[i][j], n -> val++); // (1)
}
} }
System.out.println(Arrays.deepToString(a)); System.out.println(Arrays.deepToString(a));
} }
} }
/* Output: /* Output:
[[], [[0], [0], [0, 0, 0, 0]], [[], [0, 0], [0, 0]], [[0, [[], [[1], [2], [3, 4, 5, 6]], [[], [7, 8], [9, 10]],
0, 0], [0], [0, 0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0], []], [[11, 12, 13], [14], [15, 16, 17, 18]], [[19, 20, 21],
[[0], [], [0]]] [22, 23, 24], [25], []], [[26], [], [27]]]
*/ */

View File

@ -1,25 +0,0 @@
// arrays/RandomSuppliersTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import onjava.*;
public class RandomSuppliersTest {
public static void main(String[] args) {
SuppliersTest.test(RandomSupplier.class);
}
}
/* Output:
Double: 0.73 0.53 0.16 0.19 0.52 0.27 0.26 0.05 0.8 0.76
Float: 0.53 0.16 0.53 0.4 0.49 0.25 0.8 0.11 0.02 0.8
Long: 7674 8804 8950 7826 4322 896 8033 2984 2344 5810
Integer: 8303 3141 7138 6012 9966 8689 7185 6992 5746 3976
Short: 3358 20592 284 26791 12834 -8092 13656 29324 -1423
5327
String: bkInaMe sbtWHkj UrUkZPg wsqPzDy CyRFJQA HxxHvHq
XumcXZJ oogoYWM NvqeuTp nXsgqia
Character: x x E A J J m z M s
Byte: -60 -17 55 -14 -5 115 39 -37 79 115
Boolean: false true false false true true true true true
true
*/

View File

@ -5,16 +5,15 @@
// The Collections.reverseOrder() Comparator // The Collections.reverseOrder() Comparator
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
public class Reverse { public class Reverse {
public static void main(String[] args) { public static void main(String[] args) {
CompType[] a = Generated.array( CompType[] a = new CompType[12];
new CompType[12], CompType.generator()); Arrays.setAll(a, n -> CompType.get());
System.out.println("before sorting:"); show("Before sorting", a);
System.out.println(Arrays.toString(a));
Arrays.sort(a, Collections.reverseOrder()); Arrays.sort(a, Collections.reverseOrder());
System.out.println("after sorting:"); show("After sorting", a);
System.out.println(Arrays.toString(a));
} }
} }
/* Output: /* Output:

56
arrays/SimpleSetAll.java Normal file
View File

@ -0,0 +1,56 @@
// arrays/SimpleSetAll.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import static onjava.ArrayShow.*;
class Bob {
final int id;
public Bob(int n) { id = n; }
@Override
public String toString() { return "Bob" + id; }
}
public class SimpleSetAll {
public static final int SZ = 8;
public static int val = 1;
static char[] chars = "abcdefghijklmnopqrstuvwxyz"
.toCharArray();
static char getChar(int n) { return chars[n]; }
public static void main(String[] args) {
int[] ia = new int[SZ];
long[] la = new long[SZ];
double[] da = new double[SZ];
Arrays.setAll(ia, n -> n); // (1)
Arrays.setAll(la, n -> n);
Arrays.setAll(da, n -> n);
show(ia);
show(la);
show(da);
Arrays.setAll(ia, n -> val++); // (2)
Arrays.setAll(la, n -> val++);
Arrays.setAll(da, n -> val++);
show(ia);
show(la);
show(da);
Bob[] ba = new Bob[SZ];
Arrays.setAll(ba, Bob::new); // (3)
show(ba);
Character[] ca = new Character[SZ];
Arrays.setAll(ca, SimpleSetAll::getChar); // (4)
show(ca);
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
[1, 2, 3, 4, 5, 6, 7, 8]
[9, 10, 11, 12, 13, 14, 15, 16]
[17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0]
[Bob0, Bob1, Bob2, Bob3, Bob4, Bob5, Bob6, Bob7]
[a, b, c, d, e, f, g, h]
*/

View File

@ -0,0 +1,51 @@
// arrays/StreamFromArray.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
public class StreamFromArray {
public static void main(String[] args) {
String[] s = new Rand.String().array(10);
Arrays.stream(s)
.skip(3)
.limit(5)
.map(ss -> ss + "!")
.forEach(System.out::println);
int[] ia = new Rand.int_().array(10);
Arrays.stream(ia)
.skip(3)
.limit(5)
.map(i -> i * 10)
.forEach(System.out::println);
Arrays.stream(new long[10]);
Arrays.stream(new double[10]);
// Only int, long and double work:
//- Arrays.stream(new boolean[10]);
//- Arrays.stream(new byte[10]);
//- Arrays.stream(new char[10]);
//- Arrays.stream(new short[10]);
//- Arrays.stream(new float[10]);
// For the other types you must use wrapped arrays:
float[] fa = new Rand.float_().array(10);
Arrays.stream(ConvertTo.boxed(fa));
Arrays.stream(new Rand.Float().array(10));
}
}
/* Output:
eloztdv!
ewcippc!
ygpoalk!
ljlbynx!
taprwxz!
47200
61770
84790
66560
37680
*/

View File

@ -2,25 +2,21 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Sorting an array of Strings. // Sorting an array of Strings
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*;
public class StringSorting { public class StringSorting {
public static void main(String[] args) { public static void main(String[] args) {
String[] sa = Generated.array(new String[20], String[] sa = new Rand.String().array(20);
new RandomSupplier.String(5)); show("Before sort", sa);
System.out.println(
"Before sort: " + Arrays.toString(sa));
Arrays.sort(sa); Arrays.sort(sa);
System.out.println( show("After sort", sa);
"After sort: " + Arrays.toString(sa));
Arrays.sort(sa, Collections.reverseOrder()); Arrays.sort(sa, Collections.reverseOrder());
System.out.println( show("Reverse sort", sa);
"Reverse sort: " + Arrays.toString(sa));
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER); Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
System.out.println( show("Case-insensitive sort", sa);
"Case-insensitive sort: " + Arrays.toString(sa));
} }
} }
/* Output: /* Output:

View File

@ -1,40 +0,0 @@
// arrays/SuppliersTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.function.*;
import onjava.*;
public class SuppliersTest {
public static int size = 10;
public static void test(Class<?> surroundingClass) {
for(Class<?> type : surroundingClass.getClasses()) {
System.out.print(type.getSimpleName() + ": ");
try {
Supplier<?> g = (Supplier<?>)type.newInstance();
for(int i = 0; i < size; i++)
System.out.printf(g.get() + " ");
System.out.println();
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
test(CountingSupplier.class);
}
}
/* Output:
Double: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
Float: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
Long: 0 1 2 3 4 5 6 7 8 9
Integer: 0 1 2 3 4 5 6 7 8 9
Short: 0 1 2 3 4 5 6 7 8 9
String: abcdefg hijklmn opqrstu vwxyzAB CDEFGHI JKLMNOP
QRSTUVW XYZabcd efghijk lmnopqr
Character: a b c d e f g h i j
Byte: 0 1 2 3 4 5 6 7 8 9
Boolean: true false true false true false true false true
false
*/

View File

@ -1,48 +0,0 @@
// arrays/TestArrayGeneration.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Test the tools that use generators to fill arrays.
import java.util.*;
import onjava.*;
public class TestArrayGeneration {
public static void main(String[] args) {
int size = 6;
boolean[] a1 = ConvertTo.primitive(Generated.array(
Boolean.class, new RandomSupplier.Boolean(), size));
System.out.println("a1 = " + Arrays.toString(a1));
byte[] a2 = ConvertTo.primitive(Generated.array(
Byte.class, new RandomSupplier.Byte(), size));
System.out.println("a2 = " + Arrays.toString(a2));
char[] a3 = ConvertTo.primitive(Generated.array(
Character.class,
new RandomSupplier.Character(), size));
System.out.println("a3 = " + Arrays.toString(a3));
short[] a4 = ConvertTo.primitive(Generated.array(
Short.class, new RandomSupplier.Short(), size));
System.out.println("a4 = " + Arrays.toString(a4));
int[] a5 = ConvertTo.primitive(Generated.array(
Integer.class, new RandomSupplier.Integer(), size));
System.out.println("a5 = " + Arrays.toString(a5));
long[] a6 = ConvertTo.primitive(Generated.array(
Long.class, new RandomSupplier.Long(), size));
System.out.println("a6 = " + Arrays.toString(a6));
float[] a7 = ConvertTo.primitive(Generated.array(
Float.class, new RandomSupplier.Float(), size));
System.out.println("a7 = " + Arrays.toString(a7));
double[] a8 = ConvertTo.primitive(Generated.array(
Double.class, new RandomSupplier.Double(), size));
System.out.println("a8 = " + Arrays.toString(a8));
}
}
/* Output:
a1 = [true, false, true, false, false, true]
a2 = [104, -79, -76, 126, 33, -64]
a3 = [Z, n, T, c, Q, r]
a4 = [-13408, 22612, 15401, 15161, -28466, -12603]
a5 = [7704, 7383, 7706, 575, 8410, 6342]
a6 = [7674, 8804, 8950, 7826, 4322, 896]
a7 = [0.01, 0.2, 0.4, 0.79, 0.27, 0.45]
a8 = [0.16, 0.87, 0.7, 0.66, 0.87, 0.59]
*/

87
arrays/TestConvertTo.java Normal file
View File

@ -0,0 +1,87 @@
// arrays/TestConvertTo.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
import static onjava.ConvertTo.*;
public class TestConvertTo {
static final int size = 6;
public static void main(String[] args) {
Boolean[] a1 = new Boolean[size];
Arrays.setAll(a1, new Rand.Boolean()::get);
boolean[] a1p = primitive(a1);
show("a1p", a1p);
Boolean[] a1b = boxed(a1p);
show("a1b", a1b);
Byte[] a2 = new Byte[size];
Arrays.setAll(a2, new Rand.Byte()::get);
byte[] a2p = primitive(a2);
show("a2p", a2p);
Byte[] a2b = boxed(a2p);
show("a2b", a2b);
Character[] a3 = new Character[size];
Arrays.setAll(a3, new Rand.Character()::get);
char[] a3p = primitive(a3);
show("a3p", a3p);
Character[] a3b = boxed(a3p);
show("a3b", a3b);
Short[] a4 = new Short[size];
Arrays.setAll(a4, new Rand.Short()::get);
short[] a4p = primitive(a4);
show("a4p", a4p);
Short[] a4b = boxed(a4p);
show("a4b", a4b);
Integer[] a5 = new Integer[size];
Arrays.setAll(a5, new Rand.Integer()::get);
int[] a5p = primitive(a5);
show("a5p", a5p);
Integer[] a5b = boxed(a5p);
show("a5b", a5b);
Long[] a6 = new Long[size];
Arrays.setAll(a6, new Rand.Long()::get);
long[] a6p = primitive(a6);
show("a6p", a6p);
Long[] a6b = boxed(a6p);
show("a6b", a6b);
Float[] a7 = new Float[size];
Arrays.setAll(a7, new Rand.Float()::get);
float[] a7p = primitive(a7);
show("a7p", a7p);
Float[] a7b = boxed(a7p);
show("a7b", a7b);
Double[] a8 = new Double[size];
Arrays.setAll(a8, new Rand.Double()::get);
double[] a8p = primitive(a8);
show("a8p", a8p);
Double[] a8b = boxed(a8p);
show("a8b", a8b);
}
}
/* Output:
a1p: [true, false, true, true, true, false]
a1b: [true, false, true, true, true, false]
a2p: [123, 33, 101, 112, 33, 31]
a2b: [123, 33, 101, 112, 33, 31]
a3p: [b, t, p, e, n, p]
a3b: [b, t, p, e, n, p]
a4p: [635, 8737, 3941, 4720, 6177, 8479]
a4b: [635, 8737, 3941, 4720, 6177, 8479]
a5p: [635, 8737, 3941, 4720, 6177, 8479]
a5b: [635, 8737, 3941, 4720, 6177, 8479]
a6p: [6882, 3765, 692, 9575, 4439, 2638]
a6b: [6882, 3765, 692, 9575, 4439, 2638]
a7p: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
a7b: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
a8p: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
a8b: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
*/

140
arrays/TestCount.java Normal file
View File

@ -0,0 +1,140 @@
// arrays/TestCount.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Test counting generators
import java.util.*;
import java.util.stream.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class TestCount {
static final int SZ = 5;
public static void main(String[] args) {
System.out.println("Boolean");
Boolean[] a1 = new Boolean[SZ];
Arrays.setAll(a1, new Count.Boolean()::get);
show(a1);
show(Stream.generate(new Count.Boolean())
.limit(SZ + 1).toArray());
show(new Count.Boolean().array(SZ + 2));
show(new Count.boolean_().array(SZ + 3));
System.out.println("Byte");
Byte[] a2 = new Byte[SZ];
Arrays.setAll(a2, new Count.Byte()::get);
show(a2);
show(Stream.generate(new Count.Byte())
.limit(SZ + 1).toArray());
show(new Count.Byte().array(SZ + 2));
show(new Count.byte_().array(SZ + 3));
System.out.println("Character");
Character[] a3 = new Character[SZ];
Arrays.setAll(a3, new Count.Character()::get);
show(a3);
show(Stream.generate(new Count.Character())
.limit(SZ + 1).toArray());
show(new Count.Character().array(SZ + 2));
show(new Count.char_().array(SZ + 3));
System.out.println("Short");
Short[] a4 = new Short[SZ];
Arrays.setAll(a4, new Count.Short()::get);
show(a4);
show(Stream.generate(new Count.Short())
.limit(SZ + 1).toArray());
show(new Count.Short().array(SZ + 2));
show(new Count.short_().array(SZ + 3));
System.out.println("Integer");
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Count.Integer()::get);
show(a5);
show(Stream.generate(new Count.Integer())
.limit(SZ + 1).toArray());
show(new Count.Integer().array(SZ + 2));
a5 = IntStream.generate(new Count.int_())
.limit(SZ + 1).toArray();
show(a5);
show(new Count.int_().array(SZ + 3));
System.out.println("Long");
long[] a6 = new long[SZ];
Arrays.setAll(a6, new Count.Long()::get);
show(a6);
show(Stream.generate(new Count.Long())
.limit(SZ + 1).toArray());
show(new Count.Long().array(SZ + 2));
a6 = LongStream.generate(new Count.long_())
.limit(SZ + 1).toArray();
show(a6);
show(new Count.long_().array(SZ + 3));
System.out.println("Float");
Float[] a7 = new Float[SZ];
Arrays.setAll(a7, new Count.Float()::get);
show(a7);
show(Stream.generate(new Count.Float())
.limit(SZ + 1).toArray());
show(new Count.Float().array(SZ + 2));
show(new Count.float_().array(SZ + 3));
System.out.println("Double");
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Count.Double()::get);
show(a8);
show(Stream.generate(new Count.Double())
.limit(SZ + 1).toArray());
show(new Count.Double().array(SZ + 2));
a8 = DoubleStream.generate(new Count.double_())
.limit(SZ + 1).toArray();
show(a8);
show(new Count.double_().array(SZ + 3));
}
}
/* Output:
Boolean
[false, true, false, true, false]
[false, true, false, true, false, true]
[false, true, false, true, false, true, false]
[false, true, false, true, false, true, false, true]
Byte
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
Character
[b, c, d, e, f]
[b, c, d, e, f, g]
[b, c, d, e, f, g, h]
[b, c, d, e, f, g, h, i]
Short
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
Integer
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6, 7]
Long
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6, 7]
Float
[0.0, 1.0, 2.0, 3.0, 4.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
Double
[0.0, 1.0, 2.0, 3.0, 4.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
*/

View File

@ -1,23 +0,0 @@
// arrays/TestGenerated.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
public class TestGenerated {
public static void main(String[] args) {
Integer[] a = { 9, 8, 7, 6 };
System.out.println(Arrays.toString(a));
a = Generated.array(a, new CountingSupplier.Integer());
System.out.println(Arrays.toString(a));
Integer[] b = Generated.array(Integer.class,
new CountingSupplier.Integer(), 15);
System.out.println(Arrays.toString(b));
}
}
/* Output:
[9, 8, 7, 6]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
*/

161
arrays/TestRand.java Normal file
View File

@ -0,0 +1,161 @@
// arrays/TestRand.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Test random generators
import java.util.*;
import java.util.stream.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class TestRand {
static final int SZ = 5;
public static void main(String[] args) {
System.out.println("Boolean");
Boolean[] a1 = new Boolean[SZ];
Arrays.setAll(a1, new Rand.Boolean()::get);
show(a1);
show(Stream.generate(new Rand.Boolean())
.limit(SZ + 1).toArray());
show(new Rand.Boolean().array(SZ + 2));
show(new Rand.boolean_().array(SZ + 3));
System.out.println("Byte");
Byte[] a2 = new Byte[SZ];
Arrays.setAll(a2, new Rand.Byte()::get);
show(a2);
show(Stream.generate(new Rand.Byte())
.limit(SZ + 1).toArray());
show(new Rand.Byte().array(SZ + 2));
show(new Rand.byte_().array(SZ + 3));
System.out.println("Character");
Character[] a3 = new Character[SZ];
Arrays.setAll(a3, new Rand.Character()::get);
show(a3);
show(Stream.generate(new Rand.Character())
.limit(SZ + 1).toArray());
show(new Rand.Character().array(SZ + 2));
show(new Rand.char_().array(SZ + 3));
System.out.println("Short");
Short[] a4 = new Short[SZ];
Arrays.setAll(a4, new Rand.Short()::get);
show(a4);
show(Stream.generate(new Rand.Short())
.limit(SZ + 1).toArray());
show(new Rand.Short().array(SZ + 2));
show(new Rand.short_().array(SZ + 3));
System.out.println("Integer");
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Rand.Integer()::get);
show(a5);
show(Stream.generate(new Rand.Integer())
.limit(SZ + 1).toArray());
show(new Rand.Integer().array(SZ + 2));
a5 = IntStream.generate(new Rand.int_())
.limit(SZ + 1).toArray();
show(a5);
show(new Rand.int_().array(SZ + 3));
System.out.println("Long");
long[] a6 = new long[SZ];
Arrays.setAll(a6, new Rand.Long()::get);
show(a6);
show(Stream.generate(new Rand.Long())
.limit(SZ + 1).toArray());
show(new Rand.Long().array(SZ + 2));
a6 = LongStream.generate(new Rand.long_())
.limit(SZ + 1).toArray();
show(a6);
show(new Rand.long_().array(SZ + 3));
System.out.println("Float");
Float[] a7 = new Float[SZ];
Arrays.setAll(a7, new Rand.Float()::get);
show(a7);
show(Stream.generate(new Rand.Float())
.limit(SZ + 1).toArray());
show(new Rand.Float().array(SZ + 2));
show(new Rand.float_().array(SZ + 3));
System.out.println("Double");
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Rand.Double()::get);
show(a8);
show(Stream.generate(new Rand.Double())
.limit(SZ + 1).toArray());
show(new Rand.Double().array(SZ + 2));
a8 = DoubleStream.generate(new Rand.double_())
.limit(SZ + 2).toArray();
show(a8);
show(new Rand.double_().array(SZ + 3));
System.out.println("String");
String[] s = new String[SZ - 1];
Arrays.setAll(s, new Rand.String()::get);
show(s);
show(Stream.generate(new Rand.String())
.limit(SZ).toArray());
show(new Rand.String().array(SZ + 1));
Arrays.setAll(s, new Rand.String(4)::get);
show(s);
show(Stream.generate(new Rand.String(4))
.limit(SZ).toArray());
show(new Rand.String(4).array(SZ + 1));
}
}
/* Output:
Boolean
[true, false, true, true, true]
[true, false, true, true, true, false]
[true, false, true, true, true, false, false]
[true, false, true, true, true, false, false, true]
Byte
[123, 33, 101, 112, 33]
[123, 33, 101, 112, 33, 31]
[123, 33, 101, 112, 33, 31, 0]
[123, 33, 101, 112, 33, 31, 0, -72]
Character
[b, t, p, e, n]
[b, t, p, e, n, p]
[b, t, p, e, n, p, c]
[b, t, p, e, n, p, c, c]
Short
[635, 8737, 3941, 4720, 6177]
[635, 8737, 3941, 4720, 6177, 8479]
[635, 8737, 3941, 4720, 6177, 8479, 6656]
[635, 8737, 3941, 4720, 6177, 8479, 6656, 3768]
Integer
[635, 8737, 3941, 4720, 6177]
[635, 8737, 3941, 4720, 6177, 8479]
[635, 8737, 3941, 4720, 6177, 8479, 6656]
[635, 8737, 3941, 4720, 6177, 8479]
[635, 8737, 3941, 4720, 6177, 8479, 6656, 3768]
Long
[6882, 3765, 692, 9575, 4439]
[6882, 3765, 692, 9575, 4439, 2638]
[6882, 3765, 692, 9575, 4439, 2638, 4011]
[6882, 3765, 692, 9575, 4439, 2638]
[6882, 3765, 692, 9575, 4439, 2638, 4011, 9610]
Float
[4.83, 2.89, 2.9, 1.97, 3.01]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99, 8.28]
Double
[4.83, 2.89, 2.9, 1.97, 3.01]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99, 8.28]
String
[btpenpc, cuxszgv, gmeinne, eloztdv]
[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc]
[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc, ygpoalk]
[btpe, npcc, uxsz, gvgm]
[btpe, npcc, uxsz, gvgm, einn]
[btpe, npcc, uxsz, gvgm, einn, eelo]
*/

View File

@ -8,59 +8,79 @@
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="AlphabeticSearch" /> <jrun cls="AlphabeticSearch" />
<jrun cls="ArrayCopying" />
<jrun cls="ArrayOfGenerics" /> <jrun cls="ArrayOfGenerics" />
<jrun cls="ArrayOptions" /> <jrun cls="ArrayOptions" />
<jrun cls="ArraySearching" /> <jrun cls="ArraySearching" />
<jrun cls="AssemblingMultidimensionalArrays" /> <jrun cls="AssemblingMultidimensionalArrays" />
<jrun cls="AutoboxingArrays" /> <jrun cls="AutoboxingArrays" />
<jrun cls="BadMicroBenchmark" />
<jrun cls="BadMicroBenchmark2" />
<jrun cls="BadMicroBenchmark3" />
<jrun cls="CollectionComparison" /> <jrun cls="CollectionComparison" />
<jrun cls="ComparatorTest" /> <jrun cls="ComparatorTest" />
<jrun cls="ComparingArrays" /> <jrun cls="ComparingArrays" />
<jrun cls="CompType" /> <jrun cls="CompType" />
<jrun cls="CopyingArrays" /> <jrun cls="CountUpward" />
<jrun cls="FillingArrays" /> <jrun cls="FillingArrays" />
<jrun cls="IceCream" /> <jrun cls="IceCream" />
<jrun cls="ModifyExisting" />
<jrun cls="MultidimensionalObjectArrays" /> <jrun cls="MultidimensionalObjectArrays" />
<jrun cls="MultidimensionalPrimitiveArray" /> <jrun cls="MultidimensionalPrimitiveArray" />
<jrun cls="MultiDimWrapperArray" /> <jrun cls="MultiDimWrapperArray" />
<jrun cls="ParallelPrefix" />
<jrun cls="ParallelSetAll" />
<jrun cls="ParallelSort" />
<jrun cls="ParameterizedArrayType" /> <jrun cls="ParameterizedArrayType" />
<jrun cls="PrimitiveConversionDemonstration" /> <jrun cls="Prefix1" />
<jrun cls="Prefix2" />
<jrun cls="RaggedArray" /> <jrun cls="RaggedArray" />
<jrun cls="RandomSuppliersTest" />
<jrun cls="Reverse" /> <jrun cls="Reverse" />
<jrun cls="SimpleSetAll" />
<jrun cls="StreamFromArray" />
<jrun cls="StringSorting" /> <jrun cls="StringSorting" />
<jrun cls="SuppliersTest" /> <jrun cls="TestConvertTo" />
<jrun cls="TestArrayGeneration" /> <jrun cls="TestCount" />
<jrun cls="TestGenerated" /> <jrun cls="TestRand" />
<jrun cls="ThreeDWithNew" /> <jrun cls="ThreeDWithNew" />
</target> </target>
<target name="runconsole" description="Compile and run" depends="build"> <target name="runconsole" description="Compile and run" depends="build">
<jrunconsole cls="AlphabeticSearch" /> <jrunconsole cls="AlphabeticSearch" />
<jrunconsole cls="ArrayCopying" />
<jrunconsole cls="ArrayOfGenerics" /> <jrunconsole cls="ArrayOfGenerics" />
<jrunconsole cls="ArrayOptions" /> <jrunconsole cls="ArrayOptions" />
<jrunconsole cls="ArraySearching" /> <jrunconsole cls="ArraySearching" />
<jrunconsole cls="AssemblingMultidimensionalArrays" /> <jrunconsole cls="AssemblingMultidimensionalArrays" />
<jrunconsole cls="AutoboxingArrays" /> <jrunconsole cls="AutoboxingArrays" />
<jrunconsole cls="BadMicroBenchmark" />
<jrunconsole cls="BadMicroBenchmark2" />
<jrunconsole cls="BadMicroBenchmark3" />
<jrunconsole cls="CollectionComparison" /> <jrunconsole cls="CollectionComparison" />
<jrunconsole cls="ComparatorTest" /> <jrunconsole cls="ComparatorTest" />
<jrunconsole cls="ComparingArrays" /> <jrunconsole cls="ComparingArrays" />
<jrunconsole cls="CompType" /> <jrunconsole cls="CompType" />
<jrunconsole cls="CopyingArrays" /> <jrunconsole cls="CountUpward" />
<jrunconsole cls="FillingArrays" /> <jrunconsole cls="FillingArrays" />
<jrunconsole cls="IceCream" /> <jrunconsole cls="IceCream" />
<jrunconsole cls="ModifyExisting" />
<jrunconsole cls="MultidimensionalObjectArrays" /> <jrunconsole cls="MultidimensionalObjectArrays" />
<jrunconsole cls="MultidimensionalPrimitiveArray" /> <jrunconsole cls="MultidimensionalPrimitiveArray" />
<jrunconsole cls="MultiDimWrapperArray" /> <jrunconsole cls="MultiDimWrapperArray" />
<jrunconsole cls="ParallelPrefix" />
<jrunconsole cls="ParallelSetAll" />
<jrunconsole cls="ParallelSort" />
<jrunconsole cls="ParameterizedArrayType" /> <jrunconsole cls="ParameterizedArrayType" />
<jrunconsole cls="PrimitiveConversionDemonstration" /> <jrunconsole cls="Prefix1" />
<jrunconsole cls="Prefix2" />
<jrunconsole cls="RaggedArray" /> <jrunconsole cls="RaggedArray" />
<jrunconsole cls="RandomSuppliersTest" />
<jrunconsole cls="Reverse" /> <jrunconsole cls="Reverse" />
<jrunconsole cls="SimpleSetAll" />
<jrunconsole cls="StreamFromArray" />
<jrunconsole cls="StringSorting" /> <jrunconsole cls="StringSorting" />
<jrunconsole cls="SuppliersTest" /> <jrunconsole cls="TestConvertTo" />
<jrunconsole cls="TestArrayGeneration" /> <jrunconsole cls="TestCount" />
<jrunconsole cls="TestGenerated" /> <jrunconsole cls="TestRand" />
<jrunconsole cls="ThreeDWithNew" /> <jrunconsole cls="ThreeDWithNew" />
</target> </target>

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Assert with an informative message // Assert with an information-expression
// {JVMArgs: -ea} // {JVMArgs: -ea}
// {ThrowsException} // {ThrowsException}

View File

@ -2,8 +2,8 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstration of Design by Contract (DbC) combined // Demonstration of Design by Contract (DbC)
// with white-box unit testing. // combined with white-box unit testing
// (Install libraries from www.junit.org) // (Install libraries from www.junit.org)
import java.util.*; import java.util.*;
import org.junit.Test; import org.junit.Test;
@ -24,7 +24,8 @@ public class Queue {
} }
public Queue(int size) { public Queue(int size) {
data = new Object[size]; data = new Object[size];
assert invariant(); // Must be true after construction // Must be true after construction:
assert invariant();
} }
public boolean empty() { public boolean empty() {
return !wrapped && in == out; return !wrapped && in == out;

View File

@ -42,7 +42,7 @@
files/build.xml files/build.xml
enums/build.xml enums/build.xml
annotations/build.xml annotations/build.xml
concurrency/build.xml tasks/build.xml
ui/build.xml ui/build.xml
swt/build.xml swt/build.xml
patterns/build.xml patterns/build.xml
@ -86,7 +86,7 @@
files/build.xml files/build.xml
enums/build.xml enums/build.xml
annotations/build.xml annotations/build.xml
concurrency/build.xml tasks/build.xml
patterns/build.xml patterns/build.xml
unittesting/build.xml unittesting/build.xml
assertions/build.xml assertions/build.xml

View File

@ -3,17 +3,21 @@
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// The "Adapter Method" idiom uses for-in // The "Adapter Method" idiom uses for-in
// with additional kinds of Iterables. // with additional kinds of Iterables
import java.util.*; import java.util.*;
class ReversibleArrayList<T> extends ArrayList<T> { class ReversibleArrayList<T> extends ArrayList<T> {
public ReversibleArrayList(Collection<T> c) { super(c); } public ReversibleArrayList(Collection<T> c) {
super(c);
}
public Iterable<T> reversed() { public Iterable<T> reversed() {
return new Iterable<T>() { return new Iterable<T>() {
public Iterator<T> iterator() { public Iterator<T> iterator() {
return new Iterator<T>() { return new Iterator<T>() {
int current = size() - 1; int current = size() - 1;
public boolean hasNext() { return current > -1; } public boolean hasNext() {
return current > -1;
}
public T next() { return get(current--); } public T next() { return get(current--); }
public void remove() { // Not implemented public void remove() { // Not implemented
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Adding groups of elements to Collection objects. // Adding groups of elements to Collection objects
import java.util.*; import java.util.*;
public class AddingGroups { public class AddingGroups {
@ -16,9 +16,9 @@ public class AddingGroups {
Collections.addAll(collection, 11, 12, 13, 14, 15); Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts); Collections.addAll(collection, moreInts);
// Produces a list "backed by" an array: // Produces a list "backed by" an array:
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20); List<Integer> list = Arrays.asList(16,17,18,19,20);
list.set(1, 99); // OK -- modify an element list.set(1, 99); // OK -- modify an element
// list.add(21); // Runtime error because the // list.add(21); // Runtime error; the underlying
// underlying array cannot be resized. // array cannot be resized.
} }
} }

View File

@ -14,16 +14,10 @@ public class ApplesAndOrangesWithGenerics {
for(Apple apple : apples) { for(Apple apple : apples) {
System.out.println(apple.id()); System.out.println(apple.id());
} }
// Using for-in:
for(Apple c : apples)
System.out.println(c.id());
} }
} }
/* Output: /* Output:
0 0
1 1
2 2
0
1
2
*/ */

View File

@ -20,7 +20,7 @@ public class ApplesAndOrangesWithoutGenerics {
ArrayList apples = new ArrayList(); ArrayList apples = new ArrayList();
for(int i = 0; i < 3; i++) for(int i = 0; i < 3; i++)
apples.add(new Apple()); apples.add(new Apple());
// Not prevented from adding an Orange to apples: // No problem adding an Orange to apples:
apples.add(new Orange()); apples.add(new Orange());
for(Object apple : apples) { for(Object apple : apples) {
((Apple) apple).id(); ((Apple) apple).id();

View File

@ -2,7 +2,6 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Arrays.asList() makes its best guess about type.
import java.util.*; import java.util.*;
class Snow {} class Snow {}
@ -16,21 +15,20 @@ public class AsListInference {
public static void main(String[] args) { public static void main(String[] args) {
List<Snow> snow1 = Arrays.asList( List<Snow> snow1 = Arrays.asList(
new Crusty(), new Slush(), new Powder()); new Crusty(), new Slush(), new Powder());
//- snow1.add(new Heavy()); // Exception
// Won't compile: List<Snow> snow2 = Arrays.asList(
// List<Snow> snow2 = Arrays.asList( new Light(), new Heavy());
// new Light(), new Heavy()); //- snow2.add(new Slush()); // Exception
// Compiler says:
// found : java.util.List<Powder>
// required: java.util.List<Snow>
// Collections.addAll() doesn't get confused:
List<Snow> snow3 = new ArrayList<>(); List<Snow> snow3 = new ArrayList<>();
Collections.addAll(snow3, new Light(), new Heavy()); Collections.addAll(snow3,
new Light(), new Heavy(), new Powder());
snow3.add(new Crusty());
// Give a hint using an // Hint with explicit type argument specification:
// explicit type argument specification:
List<Snow> snow4 = Arrays.<Snow>asList( List<Snow> snow4 = Arrays.<Snow>asList(
new Light(), new Heavy()); new Light(), new Heavy(), new Slush());
//- snow4.add(new Powder()); // Exception
} }
} }

View File

@ -0,0 +1,33 @@
// collections/CrossCollectionIteration2.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import typeinfo.pets.*;
import java.util.*;
public class CrossCollectionIteration2 {
public static void display(Iterable<Pet> ip) {
Iterator<Pet> it = ip.iterator();
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
}
public static void main(String[] args) {
List<Pet> pets = Pets.list(8);
LinkedList<Pet> petsLL = new LinkedList<>(pets);
HashSet<Pet> petsHS = new HashSet<>(pets);
TreeSet<Pet> petsTS = new TreeSet<>(pets);
display(pets);
display(petsLL);
display(petsHS);
display(petsTS);
}
}
/* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat
*/

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// All collections work with for-in. // All collections work with for-in
import java.util.*; import java.util.*;
public class ForInCollections { public class ForInCollections {

View File

@ -16,8 +16,8 @@ public class GenericsAndUpcasting {
apples.add(new Gala()); apples.add(new Gala());
apples.add(new Fuji()); apples.add(new Fuji());
apples.add(new Braeburn()); apples.add(new Braeburn());
for(Apple c : apples) for(Apple apple : apples)
System.out.println(c); System.out.println(apple);
} }
} }
/* Output: /* Output:

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Anything Iterable works with for-in. // Anything Iterable works with for-in
import java.util.*; import java.util.*;
public class IterableClass implements Iterable<String> { public class IterableClass implements Iterable<String> {

View File

@ -16,7 +16,8 @@ public class ListFeatures {
System.out.println("3: " + pets.contains(h)); System.out.println("3: " + pets.contains(h));
pets.remove(h); // Remove by object pets.remove(h); // Remove by object
Pet p = pets.get(2); Pet p = pets.get(2);
System.out.println("4: " + p + " " + pets.indexOf(p)); System.out.println(
"4: " + p + " " + pets.indexOf(p));
Pet cymric = new Cymric(); Pet cymric = new Cymric();
System.out.println("5: " + pets.indexOf(cymric)); System.out.println("5: " + pets.indexOf(cymric));
System.out.println("6: " + pets.remove(cymric)); System.out.println("6: " + pets.remove(cymric));

View File

@ -11,7 +11,9 @@ public class MapOfList {
petPeople = new HashMap<>(); petPeople = new HashMap<>();
static { static {
petPeople.put(new Person("Dawn"), petPeople.put(new Person("Dawn"),
Arrays.asList(new Cymric("Molly"), new Mutt("Spot"))); Arrays.asList(
new Cymric("Molly"),
new Mutt("Spot")));
petPeople.put(new Person("Kate"), petPeople.put(new Person("Kate"),
Arrays.asList(new Cat("Shackleton"), Arrays.asList(new Cat("Shackleton"),
new Cat("Elsie May"), new Dog("Margrett"))); new Cat("Elsie May"), new Dog("Margrett")));

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Adding several Adapter Methods. // Adding several Adapter Methods
import java.util.*; import java.util.*;
public class MultiIterableClass extends IterableClass { public class MultiIterableClass extends IterableClass {
@ -11,8 +11,12 @@ public class MultiIterableClass extends IterableClass {
public Iterator<String> iterator() { public Iterator<String> iterator() {
return new Iterator<String>() { return new Iterator<String>() {
int current = words.length - 1; int current = words.length - 1;
public boolean hasNext() { return current > -1; } public boolean hasNext() {
public String next() { return words[current--]; } return current > -1;
}
public String next() {
return words[current--];
}
public void remove() { // Not implemented public void remove() { // Not implemented
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

View File

@ -26,7 +26,8 @@ public class NonCollectionSequence extends PetSequence {
}; };
} }
public static void main(String[] args) { public static void main(String[] args) {
NonCollectionSequence nc = new NonCollectionSequence(); NonCollectionSequence nc =
new NonCollectionSequence();
InterfaceVsIterator.display(nc.iterator()); InterfaceVsIterator.display(nc.iterator());
} }
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Collections print themselves automatically. // Collections print themselves automatically
import java.util.*; import java.util.*;
public class PrintingCollections { public class PrintingCollections {

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Upcasting to a Queue from a LinkedList. // Upcasting to a Queue from a LinkedList
import java.util.*; import java.util.*;
public class QueueDemo { public class QueueDemo {

View File

@ -0,0 +1,25 @@
// collections/SetOfString.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
public class SetOfString {
public static void main(String[] args) {
Set<String> colors = new HashSet<>();
for(int i = 0; i < 100; i++) {
colors.add("Yellow");
colors.add("Blue");
colors.add("Red");
colors.add("Red");
colors.add("Orange");
colors.add("Yellow");
colors.add("Blue");
colors.add("Purple");
}
System.out.println(colors);
}
}
/* Output:
[Red, Yellow, Blue, Purple, Orange]
*/

View File

@ -1,19 +0,0 @@
// collections/SortedSetOfInteger.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
public class SortedSetOfInteger {
public static void main(String[] args) {
Random rand = new Random(47);
SortedSet<Integer> intset = new TreeSet<>();
for(int i = 0; i < 10000; i++)
intset.add(rand.nextInt(30));
System.out.println(intset);
}
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
*/

View File

@ -0,0 +1,25 @@
// collections/SortedSetOfString.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
public class SortedSetOfString {
public static void main(String[] args) {
Set<String> colors = new TreeSet<>();
for(int i = 0; i < 100; i++) {
colors.add("Yellow");
colors.add("Blue");
colors.add("Red");
colors.add("Red");
colors.add("Orange");
colors.add("Yellow");
colors.add("Blue");
colors.add("Purple");
}
System.out.println(colors);
}
}
/* Output:
[Blue, Orange, Purple, Red, Yellow]
*/

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Simple demonstration of HashMap. // Simple demonstration of HashMap
import java.util.*; import java.util.*;
public class Statistics { public class Statistics {
@ -12,7 +12,7 @@ public class Statistics {
for(int i = 0; i < 10000; i++) { for(int i = 0; i < 10000; i++) {
// Produce a number between 0 and 20: // Produce a number between 0 and 20:
int r = rand.nextInt(20); int r = rand.nextInt(20);
Integer freq = m.get(r); Integer freq = m.get(r); // (1)
m.put(r, freq == null ? 1 : freq + 1); m.put(r, freq == null ? 1 : freq + 1);
} }
System.out.println(m); System.out.println(m);

View File

@ -6,7 +6,8 @@ import java.util.*;
import java.nio.file.*; import java.nio.file.*;
public class UniqueWords { public class UniqueWords {
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
List<String> lines = List<String> lines =
Files.readAllLines(Paths.get("SetOperations.java")); Files.readAllLines(Paths.get("SetOperations.java"));
Set<String> words = new TreeSet<>(); Set<String> words = new TreeSet<>();

View File

@ -2,12 +2,13 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Producing an alphabetic listing. // Producing an alphabetic listing
import java.util.*; import java.util.*;
import java.nio.file.*; import java.nio.file.*;
public class UniqueWordsAlphabetic { public class UniqueWordsAlphabetic {
public static void main(String[] args) throws Exception { public static void
main(String[] args) throws Exception {
List<String> lines = List<String> lines =
Files.readAllLines(Paths.get("SetOperations.java")); Files.readAllLines(Paths.get("SetOperations.java"));
Set<String> words = Set<String> words =

View File

@ -16,6 +16,7 @@
<jrun cls="CollectionMethods" /> <jrun cls="CollectionMethods" />
<jrun cls="CollectionSequence" /> <jrun cls="CollectionSequence" />
<jrun cls="CrossCollectionIteration" /> <jrun cls="CrossCollectionIteration" />
<jrun cls="CrossCollectionIteration2" />
<jrun cls="EnvironmentVariables" /> <jrun cls="EnvironmentVariables" />
<jrun cls="ForInCollections" /> <jrun cls="ForInCollections" />
<jrun cls="GenericsAndUpcasting" /> <jrun cls="GenericsAndUpcasting" />
@ -33,10 +34,11 @@
<jrun cls="PriorityQueueDemo" /> <jrun cls="PriorityQueueDemo" />
<jrun cls="QueueDemo" /> <jrun cls="QueueDemo" />
<jrun cls="SetOfInteger" /> <jrun cls="SetOfInteger" />
<jrun cls="SetOfString" />
<jrun cls="SetOperations" /> <jrun cls="SetOperations" />
<jrun cls="SimpleCollection" /> <jrun cls="SimpleCollection" />
<jrun cls="SimpleIteration" /> <jrun cls="SimpleIteration" />
<jrun cls="SortedSetOfInteger" /> <jrun cls="SortedSetOfString" />
<jrun cls="StackCollision" /> <jrun cls="StackCollision" />
<jrun cls="StackTest" /> <jrun cls="StackTest" />
<jrun cls="Statistics" /> <jrun cls="Statistics" />
@ -54,6 +56,7 @@
<jrunconsole cls="CollectionMethods" /> <jrunconsole cls="CollectionMethods" />
<jrunconsole cls="CollectionSequence" /> <jrunconsole cls="CollectionSequence" />
<jrunconsole cls="CrossCollectionIteration" /> <jrunconsole cls="CrossCollectionIteration" />
<jrunconsole cls="CrossCollectionIteration2" />
<jrunconsole cls="EnvironmentVariables" /> <jrunconsole cls="EnvironmentVariables" />
<jrunconsole cls="ForInCollections" /> <jrunconsole cls="ForInCollections" />
<jrunconsole cls="GenericsAndUpcasting" /> <jrunconsole cls="GenericsAndUpcasting" />
@ -71,10 +74,11 @@
<jrunconsole cls="PriorityQueueDemo" /> <jrunconsole cls="PriorityQueueDemo" />
<jrunconsole cls="QueueDemo" /> <jrunconsole cls="QueueDemo" />
<jrunconsole cls="SetOfInteger" /> <jrunconsole cls="SetOfInteger" />
<jrunconsole cls="SetOfString" />
<jrunconsole cls="SetOperations" /> <jrunconsole cls="SetOperations" />
<jrunconsole cls="SimpleCollection" /> <jrunconsole cls="SimpleCollection" />
<jrunconsole cls="SimpleIteration" /> <jrunconsole cls="SimpleIteration" />
<jrunconsole cls="SortedSetOfInteger" /> <jrunconsole cls="SortedSetOfString" />
<jrunconsole cls="StackCollision" /> <jrunconsole cls="StackCollision" />
<jrunconsole cls="StackTest" /> <jrunconsole cls="StackTest" />
<jrunconsole cls="Statistics" /> <jrunconsole cls="Statistics" />

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Associates keys with values. // Associates keys with values
public class AssociativeArray<K, V> { public class AssociativeArray<K, V> {
private Object[][] pairs; private Object[][] pairs;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstration of BitSet. // Demonstration of BitSet
import java.util.*; import java.util.*;
public class Bits { public class Bits {
@ -14,7 +14,7 @@ public class Bits {
System.out.println("bit pattern: " + bbits); System.out.println("bit pattern: " + bbits);
} }
public static void main(String[] args) { public static void main(String[] args) {
Random rand = new Random(47); SplittableRandom rand = new SplittableRandom(47);
// Take the LSB of nextInt(): // Take the LSB of nextInt():
byte bt = (byte)rand.nextInt(); byte bt = (byte)rand.nextInt();
BitSet bb = new BitSet(); BitSet bb = new BitSet();

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstrates WeakHashMap. // Demonstrates WeakHashMap
import java.util.*; import java.util.*;
class Element { class Element {

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Things you can do with all Collections. // Things you can do with all Collections
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Creating a good hashCode(). // Creating a good hashCode()
import java.util.*; import java.util.*;
public class CountedString { public class CountedString {

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Java 1.0/1.1 Vector and Enumeration. // Java 1.0/1.1 Vector and Enumeration
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstrates the "fail-fast" behavior. // Demonstrates the "fail-fast" behavior
import java.util.*; import java.util.*;
public class FailFast { public class FailFast {

View File

@ -1,19 +1,19 @@
// collectionsindepth/CollectionDataGeneration.java // collectionsindepth/FilledCollectionGeneration.java
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using the Suppliers defined in the Arrays chapter. // Using the Suppliers defined in the Arrays chapter
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
public class CollectionDataGeneration { public class FilledCollectionGeneration {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(new ArrayList<>( System.out.println(new ArrayList<>(
CollectionData.list( // Convenience method FilledCollection.list( // Convenience method
new RandomSupplier.String(9), 10))); new Rand.String(9), 10)));
System.out.println(new HashSet<>( System.out.println(new HashSet<>(
new CollectionData<>( new FilledCollection<>(
new RandomSupplier.Integer(), 10))); new Rand.Integer(), 10)));
} }
} }
/* Output: /* Output:

View File

@ -1,4 +1,4 @@
// collectionsindepth/CollectionDataTest.java // collectionsindepth/FilledCollectionTest.java
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
@ -15,12 +15,13 @@ class Government implements Supplier<String> {
public String get() { return foundation[index++]; } public String get() { return foundation[index++]; }
} }
public class CollectionDataTest { public class FilledCollectionTest {
public static void main(String[] args) { public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>( Set<String> set = new LinkedHashSet<>(
new CollectionData<>(new Government(), 15)); new FilledCollection<>(new Government(), 15));
// Using the convenience method: // Using the convenience method:
set.addAll(CollectionData.list(new Government(), 15)); set.addAll(
FilledCollection.list(new Government(), 15));
System.out.println(set); System.out.println(set);
} }
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// The Collections.fill() & Collections.nCopies() methods. // The Collections.fill() & Collections.nCopies() methods
import java.util.*; import java.util.*;
class StringAddress { class StringAddress {

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Looks plausible, but doesn't work as a HashMap key. // Looks plausible, but doesn't work as a HashMap key
public class Groundhog { public class Groundhog {
protected int number; protected int number;

View File

@ -3,7 +3,7 @@
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// A class that's used as a key in a HashMap // A class that's used as a key in a HashMap
// must override hashCode() and equals(). // must override hashCode() and equals()
public class Groundhog2 extends Groundhog { public class Groundhog2 extends Groundhog {
public Groundhog2(int n) { super(n); } public Groundhog2(int n) { super(n); }

View File

@ -2,18 +2,18 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// What you can do with a LinkedHashMap. // What you can do with a LinkedHashMap
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
public class LinkedHashMapDemo { public class LinkedHashMapDemo {
public static void main(String[] args) { public static void main(String[] args) {
LinkedHashMap<Integer,String> linkedMap = LinkedHashMap<Integer,String> linkedMap =
new LinkedHashMap<>(new CountingMapData(9)); new LinkedHashMap<>(new CountingFilledMap(9));
System.out.println(linkedMap); System.out.println(linkedMap);
// Least-recently-used order: // Least-recently-used order:
linkedMap = new LinkedHashMap<>(16, 0.75f, true); linkedMap = new LinkedHashMap<>(16, 0.75f, true);
linkedMap.putAll(new CountingMapData(9)); linkedMap.putAll(new CountingFilledMap(9));
System.out.println(linkedMap); System.out.println(linkedMap);
for(int i = 0; i < 6; i++) // Cause accesses: for(int i = 0; i < 6; i++) // Cause accesses:
linkedMap.get(i); linkedMap.get(i);

View File

@ -2,13 +2,13 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstrates performance differences in Lists. // Demonstrates performance differences in Lists
// {Args: 100 500} Small to keep build testing short // {Args: 100 500} Small to keep build testing short
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
public class ListPerformance { public class ListPerformance {
static Random rand = new Random(); static SplittableRandom rand = new SplittableRandom();
static int reps = 1000; static int reps = 1000;
static List<Test<List<Integer>>> tests = static List<Test<List<Integer>>> tests =
new ArrayList<>(); new ArrayList<>();
@ -53,7 +53,8 @@ public class ListPerformance {
int test(List<Integer> list, TestParam tp) { int test(List<Integer> list, TestParam tp) {
final int LOOPS = 1000000; final int LOOPS = 1000000;
int half = list.size() / 2; int half = list.size() / 2;
ListIterator<Integer> it = list.listIterator(half); ListIterator<Integer> it =
list.listIterator(half);
for(int i = 0; i < LOOPS; i++) for(int i = 0; i < LOOPS; i++)
it.add(47); it.add(47);
return LOOPS; return LOOPS;
@ -145,7 +146,8 @@ public class ListPerformance {
super(collection, tests); super(collection, tests);
} }
// Fill to the appropriate size before each test: // Fill to the appropriate size before each test:
@Override protected List<Integer> initialize(int size){ @Override
protected List<Integer> initialize(int size) {
collection.clear(); collection.clear();
collection.addAll(new CountingIntegerList(size)); collection.addAll(new CountingIntegerList(size));
return collection; return collection;
@ -161,13 +163,14 @@ public class ListPerformance {
Tester.defaultParams = TestParam.array(args); Tester.defaultParams = TestParam.array(args);
// Can only do these two tests on an array: // Can only do these two tests on an array:
Tester<List<Integer>> arrayTest = Tester<List<Integer>> arrayTest =
new Tester<List<Integer>>(null, tests.subList(1, 3)){ new Tester<List<Integer>>(null,
tests.subList(1, 3)) {
// This is called before each test. It // This is called before each test. It
// produces a non-resizeable array-backed list: // produces a non-resizeable array-backed list:
@Override protected @Override protected
List<Integer> initialize(int size) { List<Integer> initialize(int size) {
Integer[] ia = Generated.array(Integer.class, Integer[] ia = new Integer[size];
new CountingSupplier.Integer(), size); Arrays.setAll(ia, new Count.Integer()::get);
return Arrays.asList(ia); return Arrays.asList(ia);
} }
}; };

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Sorting and searching Lists with Collections utilities. // Sorting and searching Lists with Collections utilities
import java.util.*; import java.util.*;
public class ListSortSearch { public class ListSortSearch {
@ -28,7 +28,8 @@ public class ListSortSearch {
"Location of " + key + " is " + index + "Location of " + key + " is " + index +
", list.get(" + index + ") = " + list.get(index)); ", list.get(" + index + ") = " + list.get(index));
Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println("Case-insensitive sorted: " + list); System.out.println(
"Case-insensitive sorted: " + list);
key = list.get(7); key = list.get(7);
index = Collections.binarySearch(list, key, index = Collections.binarySearch(list, key,
String.CASE_INSENSITIVE_ORDER); String.CASE_INSENSITIVE_ORDER);

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