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

View File

@ -22,7 +22,8 @@ public class AtUnitExample1 {
// Shows output for failure:
@Test boolean failureTest() { 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 .. " +
"onjava.atunit.AtUnit AtUnitExample1.class");
}

View File

@ -2,7 +2,7 @@
// (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.
// Assertions and exceptions can be used in @Tests.
// Assertions and exceptions can be used in @Tests
package annotations;
import java.io.*;
import onjava.atunit.*;
@ -30,7 +30,8 @@ public class AtUnitExample2 {
assert methodTwo() == 2: "methodTwo must equal 2";
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 .. " +
"onjava.atunit.AtUnit AtUnitExample2.class");
}

View File

@ -25,7 +25,8 @@ public class AtUnitExample3 {
return methodOne().equals("This is methodOne");
}
@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 .. " +
"onjava.atunit.AtUnit AtUnitExample3.class");
}

View File

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

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// Creating non-embedded tests.
// Creating non-embedded tests
package annotations;
import onjava.atunit.*;
import onjava.*;
@ -12,7 +12,8 @@ public class AtUnitExternalTest extends AtUnitExample1 {
return methodOne().equals("This is methodOne");
}
@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 .. " +
"onjava.atunit.AtUnit AtUnitExternalTest.class");
}

View File

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

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// A stack built on a linkedList.
// A stack built on a linkedList
package annotations;
import java.util.*;

View File

@ -2,7 +2,7 @@
// (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.
// Applying @Unit to generics.
// Applying @Unit to generics
package annotations;
import onjava.atunit.*;
import onjava.*;
@ -26,7 +26,8 @@ public class StackLStringTest extends StackL<String> {
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 .. " +
"onjava.atunit.AtUnit StackLStringTest.class");
}

View File

@ -17,7 +17,8 @@ public class UseCaseTracker {
}
}
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) {

View File

@ -2,7 +2,7 @@
// (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.
// Reflection-based annotation processor.
// Reflection-based annotation processor
// {Args: annotations.database.Member}
package annotations.database;
import java.lang.annotation.*;
@ -10,7 +10,8 @@ import java.lang.reflect.*;
import java.util.*;
public class TableCreator {
public static void main(String[] args) throws Exception {
public static void
main(String[] args) throws Exception {
if(args.length < 1) {
System.out.println("arguments: annotated classes");
System.exit(0);
@ -30,7 +31,8 @@ public class TableCreator {
List<String> columnDefs = new ArrayList<>();
for(Field field : cl.getDeclaredFields()) {
String columnName = null;
Annotation[] anns = field.getDeclaredAnnotations();
Annotation[] anns =
field.getDeclaredAnnotations();
if(anns.length < 1)
continue; // Not a db table column
if(anns[0] instanceof SQLInteger) {
@ -57,7 +59,8 @@ public class TableCreator {
StringBuilder createCommand = new StringBuilder(
"CREATE TABLE " + tableName + "(");
for(String columnDef : columnDefs)
createCommand.append("\n " + columnDef + ",");
createCommand.append(
"\n " + columnDef + ",");
// Remove trailing comma
String tableCreate = createCommand.substring(
0, createCommand.length() - 1) + ");";

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// javac-based annotation processing.
// javac-based annotation processing
package annotations.ifx;
import java.lang.annotation.*;

View File

@ -2,7 +2,7 @@
// (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.
// javac-based annotation processing.
// javac-based annotation processing
package annotations.ifx;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
@ -51,8 +51,8 @@ extends AbstractProcessor {
private void
writeInterfaceFile(String interfaceName) {
try(Writer writer = processingEnv.getFiler()
.createSourceFile(interfaceName)
.openWriter()) {
.createSourceFile(interfaceName)
.openWriter()) {
String packageName = elementUtils
.getPackageOf(interfaceMethods
.get(0)).toString();

View File

@ -2,7 +2,7 @@
// (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.
// javac-based annotation processing.
// javac-based annotation processing
package annotations.ifx;
@ExtractInterface(interfaceName="IMultiplier")

View File

@ -2,7 +2,7 @@
// (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.
// A bare-bones annotation.
// A bare-bones annotation
package annotations.simplest;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

View File

@ -2,7 +2,7 @@
// (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.
// A bare-bones annotation processor.
// A bare-bones annotation processor
package annotations.simplest;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;

View File

@ -2,19 +2,20 @@
// (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.
// Searching with a Comparator.
// Searching with a Comparator
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class AlphabeticSearch {
public static void main(String[] args) {
String[] sa = Generated.array(new String[30],
new RandomSupplier.String(5));
String[] sa = new Rand.String().array(30);
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(sa));
show(sa);
int index = Arrays.binarySearch(sa, sa[10],
String.CASE_INSENSITIVE_ORDER);
System.out.println("Index: "+ index + "\n"+ sa[index]);
System.out.println(
"Index: "+ index + "\n"+ sa[index]);
}
}
/* 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
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Arrays of generic types won't compile.
public class ArrayOfGenericType<T> {
T[] array; // OK
@SuppressWarnings("unchecked")
public ArrayOfGenericType(int size) {
//- array = new T[size]; // Illegal
array = (T[])new Object[size]; // "unchecked" Warning
// error: generic array creation:
// - array = new T[size];
array = (T[])new Object[size]; // unchecked cast
}
// Illegal:
// error: generic array creation:
//- public <U> U[] makeArray() { return new U[10]; }
}

View File

@ -2,7 +2,6 @@
// (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.
// It is possible to create arrays of generics.
import java.util.*;
public class ArrayOfGenerics {
@ -10,10 +9,14 @@ public class ArrayOfGenerics {
public static void main(String[] args) {
List<String>[] ls;
List[] la = new List[10];
ls = (List<String>[])la; // "Unchecked" warning
ls = (List<String>[])la; // Unchecked cast
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
Object[] objects = ls; // So assignment is OK
@ -22,10 +25,9 @@ public class ArrayOfGenerics {
// However, if your needs are straightforward it is
// possible to create an array of generics, albeit
// with an "unchecked" warning:
// with an "unchecked cast" warning:
List<BerylliumSphere>[] spheres =
(List<BerylliumSphere>[])new List[10];
for(int i = 0; i < spheres.length; i++)
spheres[i] = new ArrayList<>();
Arrays.setAll(spheres, n -> new ArrayList<>());
}
}

View File

@ -2,8 +2,9 @@
// (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.
// Initialization & re-assignment of arrays.
// Initialization & re-assignment of arrays
import java.util.*;
import static onjava.ArrayShow.*;
public class ArrayOptions {
public static void main(String[] args) {
@ -13,23 +14,25 @@ public class ArrayOptions {
// The references inside the array are
// automatically initialized to null:
System.out.println("b: " + Arrays.toString(b));
show("b", b);
BerylliumSphere[] c = new BerylliumSphere[4];
for(int i = 0; i < c.length; i++)
if(c[i] == null) // Can test for null reference
c[i] = new BerylliumSphere();
// Aggregate initialization:
BerylliumSphere[] d = { new BerylliumSphere(),
new BerylliumSphere(), new BerylliumSphere()
BerylliumSphere[] d = {
new BerylliumSphere(),
new BerylliumSphere(),
new BerylliumSphere()
};
// Dynamic aggregate initialization:
a = 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("b.length = " + b.length);
System.out.println("c.length = " + c.length);
@ -43,14 +46,14 @@ public class ArrayOptions {
// The primitives inside the array are
// automatically initialized to zero:
System.out.println("f: " + Arrays.toString(f));
show("f", f);
int[] g = new int[4];
for(int i = 0; i < g.length; i++)
g[i] = i*i;
int[] h = { 11, 47, 93 };
// 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("g.length = " + g.length);
System.out.println("h.length = " + h.length);

View File

@ -2,35 +2,32 @@
// (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 Arrays.binarySearch().
// Using Arrays.binarySearch()
import java.util.*;
import java.util.function.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class ArraySearching {
public static void main(String[] args) {
Supplier<Integer> gen =
new RandomSupplier.Integer(1000);
int[] a = ConvertTo.primitive(
Generated.array(new Integer[25], gen));
Rand.int_ rand = new Rand.int_();
int[] a = new Rand.int_().array(25);
Arrays.sort(a);
System.out.println(
"Sorted array: " + Arrays.toString(a));
show("Sorted array", a);
while(true) {
int r = gen.get();
int r = rand.getAsInt();
int location = Arrays.binarySearch(a, r);
if(location >= 0) {
System.out.println(
"Location of " + r + " is " + location +
", a[" + location + "] = " + a[location]);
", a[" + location + "] is " + a[location]);
break; // Out of while loop
}
}
}
}
/* Output:
Sorted array: [128, 140, 200, 207, 258, 258, 278, 288, 322,
429, 511, 520, 522, 551, 555, 589, 693, 704, 809, 861, 861,
868, 916, 961, 998]
Location of 322 is 8, a[8] = 322
Sorted array: [125, 267, 635, 650, 1131, 1506, 1634,
2400, 2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070,
5682, 5807, 6177, 6193, 6656, 7021, 8479, 8737, 9954]
Location of 635 is 2, a[2] is 635
*/

View File

@ -2,7 +2,7 @@
// (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.
// Creating multidimensional arrays.
// Creating multidimensional arrays
import java.util.*;
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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
class BerylliumSphere {
private static long counter;
@ -16,17 +18,16 @@ public class CollectionComparison {
BerylliumSphere[] spheres = new BerylliumSphere[10];
for(int i = 0; i < 5; i++)
spheres[i] = new BerylliumSphere();
System.out.println(Arrays.toString(spheres));
show(spheres);
System.out.println(spheres[4]);
List<BerylliumSphere> sphereList= new ArrayList<>();
for(int i = 0; i < 5; i++)
sphereList.add(new BerylliumSphere());
List<BerylliumSphere> sphereList = Suppliers.create(
ArrayList::new, BerylliumSphere::new, 5);
System.out.println(sphereList);
System.out.println(sphereList.get(4));
int[] integers = { 0, 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(integers));
show(integers);
System.out.println(integers[4]);
List<Integer> intList = new ArrayList<>(

View File

@ -2,10 +2,11 @@
// (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.
// Implementing Comparable in a class.
// Implementing Comparable in a class
import java.util.*;
import java.util.function.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class CompType implements Comparable<CompType> {
int i;
@ -26,19 +27,17 @@ public class CompType implements Comparable<CompType> {
public int compareTo(CompType rv) {
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
}
private static Random r = new Random(47);
public static Supplier<CompType> generator() {
return () ->
new CompType(r.nextInt(100), r.nextInt(100));
private static SplittableRandom r =
new SplittableRandom(47);
public static CompType get() {
return new CompType(r.nextInt(100), r.nextInt(100));
}
public static void main(String[] args) {
CompType[] a =
Generated.array(new CompType[12], generator());
System.out.println("before sorting:");
System.out.println(Arrays.toString(a));
CompType[] a = new CompType[12];
Arrays.setAll(a, n -> get());
show("Before sorting", a);
Arrays.sort(a);
System.out.println("after sorting:");
System.out.println(Arrays.toString(a));
show("After sorting", a);
}
}
/* Output:

View File

@ -2,9 +2,10 @@
// (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.
// Implementing a Comparator for a class.
// Implementing a Comparator for a class
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
class CompTypeComparator implements Comparator<CompType> {
public int compare(CompType o1, CompType o2) {
@ -14,13 +15,11 @@ class CompTypeComparator implements Comparator<CompType> {
public class ComparatorTest {
public static void main(String[] args) {
CompType[] a = Generated.array(
new CompType[12], CompType.generator());
System.out.println("before sorting:");
System.out.println(Arrays.toString(a));
CompType[] a = new CompType[12];
Arrays.setAll(a, n -> CompType.get());
show("Before sorting", a);
Arrays.sort(a, new CompTypeComparator());
System.out.println("after sorting:");
System.out.println(Arrays.toString(a));
show("After sorting", a);
}
}
/* Output:

View File

@ -4,25 +4,57 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Using Arrays.equals()
import java.util.*;
import onjava.*;
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) {
int[] a1 = new int[10];
int[] a2 = new int[10];
Arrays.fill(a1, 47);
Arrays.fill(a2, 47);
System.out.println(Arrays.equals(a1, a2));
int[] a1 = new int[SZ], a2 = new int[SZ];
Arrays.setAll(a1, new Count.Integer()::get);
Arrays.setAll(a2, new Count.Integer()::get);
System.out.println(
"a1 == a2: " + Arrays.equals(a1, a2));
a2[3] = 11;
System.out.println(Arrays.equals(a1, a2));
String[] s1 = new String[4];
Arrays.fill(s1, "Hi");
String[] s2 = { new String("Hi"), new String("Hi"),
new String("Hi"), new String("Hi") };
System.out.println(Arrays.equals(s1, s2));
System.out.println(
"a1 == a2: " + Arrays.equals(a1, a2));
Integer[] a1w = new Integer[SZ],
a2w = new Integer[SZ];
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:
true
false
true
a1 == a2: true
a1 == a2: false
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.
// Using Arrays.fill()
import java.util.*;
import static onjava.ArrayShow.*;
public class FillingArrays {
public static void main(String[] args) {
@ -18,26 +19,26 @@ public class FillingArrays {
double[] a8 = new double[size];
String[] a9 = new String[size];
Arrays.fill(a1, true);
System.out.println("a1 = " + Arrays.toString(a1));
show("a1", a1);
Arrays.fill(a2, (byte)11);
System.out.println("a2 = " + Arrays.toString(a2));
show("a2", a2);
Arrays.fill(a3, 'x');
System.out.println("a3 = " + Arrays.toString(a3));
show("a3", a3);
Arrays.fill(a4, (short)17);
System.out.println("a4 = " + Arrays.toString(a4));
show("a4", a4);
Arrays.fill(a5, 19);
System.out.println("a5 = " + Arrays.toString(a5));
show("a5", a5);
Arrays.fill(a6, 23);
System.out.println("a6 = " + Arrays.toString(a6));
show("a6", a6);
Arrays.fill(a7, 29);
System.out.println("a7 = " + Arrays.toString(a7));
show("a7", a7);
Arrays.fill(a8, 47);
System.out.println("a8 = " + Arrays.toString(a8));
show("a8", a8);
Arrays.fill(a9, "Hello");
System.out.println("a9 = " + Arrays.toString(a9));
show("a9", a9);
// Manipulating ranges:
Arrays.fill(a9, 3, 5, "World");
System.out.println("a9 = " + Arrays.toString(a9));
show("a9", a9);
}
}
/* Output:

View File

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

View File

@ -2,7 +2,6 @@
// (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.
// Creating multidimensional arrays.
import java.util.*;
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)
print(type(list2)) # <class '__main__.MyList'>
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.*;
public class RaggedArray {
static int val = 1;
public static void main(String[] args) {
Random rand = new Random(47);
SplittableRandom rand = new SplittableRandom(47);
// 3-D array with varied-length vectors:
int[][][] a = new int[rand.nextInt(7)][][];
for(int i = 0; i < a.length; i++) {
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)];
Arrays.setAll(a[i][j], n -> val++); // (1)
}
}
System.out.println(Arrays.deepToString(a));
}
}
/* Output:
[[], [[0], [0], [0, 0, 0, 0]], [[], [0, 0], [0, 0]], [[0,
0, 0], [0], [0, 0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0], []],
[[0], [], [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]]]
*/

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
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class Reverse {
public static void main(String[] args) {
CompType[] a = Generated.array(
new CompType[12], CompType.generator());
System.out.println("before sorting:");
System.out.println(Arrays.toString(a));
CompType[] a = new CompType[12];
Arrays.setAll(a, n -> CompType.get());
show("Before sorting", a);
Arrays.sort(a, Collections.reverseOrder());
System.out.println("after sorting:");
System.out.println(Arrays.toString(a));
show("After sorting", a);
}
}
/* 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
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Sorting an array of Strings.
// Sorting an array of Strings
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
public class StringSorting {
public static void main(String[] args) {
String[] sa = Generated.array(new String[20],
new RandomSupplier.String(5));
System.out.println(
"Before sort: " + Arrays.toString(sa));
String[] sa = new Rand.String().array(20);
show("Before sort", sa);
Arrays.sort(sa);
System.out.println(
"After sort: " + Arrays.toString(sa));
show("After sort", sa);
Arrays.sort(sa, Collections.reverseOrder());
System.out.println(
"Reverse sort: " + Arrays.toString(sa));
show("Reverse sort", sa);
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
System.out.println(
"Case-insensitive sort: " + Arrays.toString(sa));
show("Case-insensitive sort", sa);
}
}
/* 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">
<jrun cls="AlphabeticSearch" />
<jrun cls="ArrayCopying" />
<jrun cls="ArrayOfGenerics" />
<jrun cls="ArrayOptions" />
<jrun cls="ArraySearching" />
<jrun cls="AssemblingMultidimensionalArrays" />
<jrun cls="AutoboxingArrays" />
<jrun cls="BadMicroBenchmark" />
<jrun cls="BadMicroBenchmark2" />
<jrun cls="BadMicroBenchmark3" />
<jrun cls="CollectionComparison" />
<jrun cls="ComparatorTest" />
<jrun cls="ComparingArrays" />
<jrun cls="CompType" />
<jrun cls="CopyingArrays" />
<jrun cls="CountUpward" />
<jrun cls="FillingArrays" />
<jrun cls="IceCream" />
<jrun cls="ModifyExisting" />
<jrun cls="MultidimensionalObjectArrays" />
<jrun cls="MultidimensionalPrimitiveArray" />
<jrun cls="MultiDimWrapperArray" />
<jrun cls="ParallelPrefix" />
<jrun cls="ParallelSetAll" />
<jrun cls="ParallelSort" />
<jrun cls="ParameterizedArrayType" />
<jrun cls="PrimitiveConversionDemonstration" />
<jrun cls="Prefix1" />
<jrun cls="Prefix2" />
<jrun cls="RaggedArray" />
<jrun cls="RandomSuppliersTest" />
<jrun cls="Reverse" />
<jrun cls="SimpleSetAll" />
<jrun cls="StreamFromArray" />
<jrun cls="StringSorting" />
<jrun cls="SuppliersTest" />
<jrun cls="TestArrayGeneration" />
<jrun cls="TestGenerated" />
<jrun cls="TestConvertTo" />
<jrun cls="TestCount" />
<jrun cls="TestRand" />
<jrun cls="ThreeDWithNew" />
</target>
<target name="runconsole" description="Compile and run" depends="build">
<jrunconsole cls="AlphabeticSearch" />
<jrunconsole cls="ArrayCopying" />
<jrunconsole cls="ArrayOfGenerics" />
<jrunconsole cls="ArrayOptions" />
<jrunconsole cls="ArraySearching" />
<jrunconsole cls="AssemblingMultidimensionalArrays" />
<jrunconsole cls="AutoboxingArrays" />
<jrunconsole cls="BadMicroBenchmark" />
<jrunconsole cls="BadMicroBenchmark2" />
<jrunconsole cls="BadMicroBenchmark3" />
<jrunconsole cls="CollectionComparison" />
<jrunconsole cls="ComparatorTest" />
<jrunconsole cls="ComparingArrays" />
<jrunconsole cls="CompType" />
<jrunconsole cls="CopyingArrays" />
<jrunconsole cls="CountUpward" />
<jrunconsole cls="FillingArrays" />
<jrunconsole cls="IceCream" />
<jrunconsole cls="ModifyExisting" />
<jrunconsole cls="MultidimensionalObjectArrays" />
<jrunconsole cls="MultidimensionalPrimitiveArray" />
<jrunconsole cls="MultiDimWrapperArray" />
<jrunconsole cls="ParallelPrefix" />
<jrunconsole cls="ParallelSetAll" />
<jrunconsole cls="ParallelSort" />
<jrunconsole cls="ParameterizedArrayType" />
<jrunconsole cls="PrimitiveConversionDemonstration" />
<jrunconsole cls="Prefix1" />
<jrunconsole cls="Prefix2" />
<jrunconsole cls="RaggedArray" />
<jrunconsole cls="RandomSuppliersTest" />
<jrunconsole cls="Reverse" />
<jrunconsole cls="SimpleSetAll" />
<jrunconsole cls="StreamFromArray" />
<jrunconsole cls="StringSorting" />
<jrunconsole cls="SuppliersTest" />
<jrunconsole cls="TestArrayGeneration" />
<jrunconsole cls="TestGenerated" />
<jrunconsole cls="TestConvertTo" />
<jrunconsole cls="TestCount" />
<jrunconsole cls="TestRand" />
<jrunconsole cls="ThreeDWithNew" />
</target>

View File

@ -2,7 +2,7 @@
// (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.
// Assert with an informative message
// Assert with an information-expression
// {JVMArgs: -ea}
// {ThrowsException}

View File

@ -2,8 +2,8 @@
// (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.
// Demonstration of Design by Contract (DbC) combined
// with white-box unit testing.
// Demonstration of Design by Contract (DbC)
// combined with white-box unit testing
// (Install libraries from www.junit.org)
import java.util.*;
import org.junit.Test;
@ -24,7 +24,8 @@ public class Queue {
}
public Queue(int size) {
data = new Object[size];
assert invariant(); // Must be true after construction
// Must be true after construction:
assert invariant();
}
public boolean empty() {
return !wrapped && in == out;

View File

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

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// Adding groups of elements to Collection objects.
// Adding groups of elements to Collection objects
import java.util.*;
public class AddingGroups {
@ -16,9 +16,9 @@ public class AddingGroups {
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);
// 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.add(21); // Runtime error because the
// underlying array cannot be resized.
// list.add(21); // Runtime error; the underlying
// array cannot be resized.
}
}

View File

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

View File

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

View File

@ -2,7 +2,6 @@
// (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.
// Arrays.asList() makes its best guess about type.
import java.util.*;
class Snow {}
@ -16,21 +15,20 @@ public class AsListInference {
public static void main(String[] args) {
List<Snow> snow1 = Arrays.asList(
new Crusty(), new Slush(), new Powder());
//- snow1.add(new Heavy()); // Exception
// Won't compile:
// List<Snow> snow2 = Arrays.asList(
// new Light(), new Heavy());
// Compiler says:
// found : java.util.List<Powder>
// required: java.util.List<Snow>
List<Snow> snow2 = Arrays.asList(
new Light(), new Heavy());
//- snow2.add(new Slush()); // Exception
// Collections.addAll() doesn't get confused:
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
// explicit type argument specification:
// Hint with explicit type argument specification:
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
// We make no guarantees that this code is fit for any purpose.
// 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.*;
public class ForInCollections {

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// Anything Iterable works with for-in.
// Anything Iterable works with for-in
import java.util.*;
public class IterableClass implements Iterable<String> {

View File

@ -16,7 +16,8 @@ public class ListFeatures {
System.out.println("3: " + pets.contains(h));
pets.remove(h); // Remove by object
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();
System.out.println("5: " + pets.indexOf(cymric));
System.out.println("6: " + pets.remove(cymric));

View File

@ -11,7 +11,9 @@ public class MapOfList {
petPeople = new HashMap<>();
static {
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"),
Arrays.asList(new Cat("Shackleton"),
new Cat("Elsie May"), new Dog("Margrett")));

View File

@ -2,7 +2,7 @@
// (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.
// Adding several Adapter Methods.
// Adding several Adapter Methods
import java.util.*;
public class MultiIterableClass extends IterableClass {
@ -11,8 +11,12 @@ public class MultiIterableClass extends IterableClass {
public Iterator<String> iterator() {
return new Iterator<String>() {
int current = words.length - 1;
public boolean hasNext() { return current > -1; }
public String next() { return words[current--]; }
public boolean hasNext() {
return current > -1;
}
public String next() {
return words[current--];
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// Collections print themselves automatically.
// Collections print themselves automatically
import java.util.*;
public class PrintingCollections {

View File

@ -2,7 +2,7 @@
// (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.
// Upcasting to a Queue from a LinkedList.
// Upcasting to a Queue from a LinkedList
import java.util.*;
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
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Simple demonstration of HashMap.
// Simple demonstration of HashMap
import java.util.*;
public class Statistics {
@ -12,7 +12,7 @@ public class Statistics {
for(int i = 0; i < 10000; i++) {
// Produce a number between 0 and 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);
}
System.out.println(m);

View File

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

View File

@ -2,12 +2,13 @@
// (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.
// Producing an alphabetic listing.
// Producing an alphabetic listing
import java.util.*;
import java.nio.file.*;
public class UniqueWordsAlphabetic {
public static void main(String[] args) throws Exception {
public static void
main(String[] args) throws Exception {
List<String> lines =
Files.readAllLines(Paths.get("SetOperations.java"));
Set<String> words =

View File

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

View File

@ -2,7 +2,7 @@
// (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.
// Associates keys with values.
// Associates keys with values
public class AssociativeArray<K, V> {
private Object[][] pairs;

View File

@ -2,7 +2,7 @@
// (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.
// Demonstration of BitSet.
// Demonstration of BitSet
import java.util.*;
public class Bits {
@ -14,7 +14,7 @@ public class Bits {
System.out.println("bit pattern: " + bbits);
}
public static void main(String[] args) {
Random rand = new Random(47);
SplittableRandom rand = new SplittableRandom(47);
// Take the LSB of nextInt():
byte bt = (byte)rand.nextInt();
BitSet bb = new BitSet();

View File

@ -2,7 +2,7 @@
// (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.
// Demonstrates WeakHashMap.
// Demonstrates WeakHashMap
import java.util.*;
class Element {

View File

@ -2,7 +2,7 @@
// (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.
// Things you can do with all Collections.
// Things you can do with all Collections
import java.util.*;
import onjava.*;

View File

@ -2,7 +2,7 @@
// (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.
// Creating a good hashCode().
// Creating a good hashCode()
import java.util.*;
public class CountedString {

View File

@ -2,7 +2,7 @@
// (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.
// Java 1.0/1.1 Vector and Enumeration.
// Java 1.0/1.1 Vector and Enumeration
import java.util.*;
import onjava.*;

View File

@ -2,7 +2,7 @@
// (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.
// Demonstrates the "fail-fast" behavior.
// Demonstrates the "fail-fast" behavior
import java.util.*;
public class FailFast {

View File

@ -1,19 +1,19 @@
// collectionsindepth/CollectionDataGeneration.java
// collectionsindepth/FilledCollectionGeneration.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 the Suppliers defined in the Arrays chapter.
// Using the Suppliers defined in the Arrays chapter
import java.util.*;
import onjava.*;
public class CollectionDataGeneration {
public class FilledCollectionGeneration {
public static void main(String[] args) {
System.out.println(new ArrayList<>(
CollectionData.list( // Convenience method
new RandomSupplier.String(9), 10)));
FilledCollection.list( // Convenience method
new Rand.String(9), 10)));
System.out.println(new HashSet<>(
new CollectionData<>(
new RandomSupplier.Integer(), 10)));
new FilledCollection<>(
new Rand.Integer(), 10)));
}
}
/* Output:

View File

@ -1,4 +1,4 @@
// collectionsindepth/CollectionDataTest.java
// collectionsindepth/FilledCollectionTest.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.
@ -15,12 +15,13 @@ class Government implements Supplier<String> {
public String get() { return foundation[index++]; }
}
public class CollectionDataTest {
public class FilledCollectionTest {
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>(
new CollectionData<>(new Government(), 15));
new FilledCollection<>(new Government(), 15));
// Using the convenience method:
set.addAll(CollectionData.list(new Government(), 15));
set.addAll(
FilledCollection.list(new Government(), 15));
System.out.println(set);
}
}

View File

@ -2,7 +2,7 @@
// (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.
// The Collections.fill() & Collections.nCopies() methods.
// The Collections.fill() & Collections.nCopies() methods
import java.util.*;
class StringAddress {

View File

@ -2,7 +2,7 @@
// (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.
// Looks plausible, but doesn't work as a HashMap key.
// Looks plausible, but doesn't work as a HashMap key
public class Groundhog {
protected int number;

View File

@ -3,7 +3,7 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// 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 Groundhog2(int n) { super(n); }

View File

@ -2,18 +2,18 @@
// (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.
// What you can do with a LinkedHashMap.
// What you can do with a LinkedHashMap
import java.util.*;
import onjava.*;
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<Integer,String> linkedMap =
new LinkedHashMap<>(new CountingMapData(9));
new LinkedHashMap<>(new CountingFilledMap(9));
System.out.println(linkedMap);
// Least-recently-used order:
linkedMap = new LinkedHashMap<>(16, 0.75f, true);
linkedMap.putAll(new CountingMapData(9));
linkedMap.putAll(new CountingFilledMap(9));
System.out.println(linkedMap);
for(int i = 0; i < 6; i++) // Cause accesses:
linkedMap.get(i);

View File

@ -2,13 +2,13 @@
// (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.
// Demonstrates performance differences in Lists.
// Demonstrates performance differences in Lists
// {Args: 100 500} Small to keep build testing short
import java.util.*;
import onjava.*;
public class ListPerformance {
static Random rand = new Random();
static SplittableRandom rand = new SplittableRandom();
static int reps = 1000;
static List<Test<List<Integer>>> tests =
new ArrayList<>();
@ -53,7 +53,8 @@ public class ListPerformance {
int test(List<Integer> list, TestParam tp) {
final int LOOPS = 1000000;
int half = list.size() / 2;
ListIterator<Integer> it = list.listIterator(half);
ListIterator<Integer> it =
list.listIterator(half);
for(int i = 0; i < LOOPS; i++)
it.add(47);
return LOOPS;
@ -145,7 +146,8 @@ public class ListPerformance {
super(collection, tests);
}
// 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.addAll(new CountingIntegerList(size));
return collection;
@ -161,13 +163,14 @@ public class ListPerformance {
Tester.defaultParams = TestParam.array(args);
// Can only do these two tests on an array:
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
// produces a non-resizeable array-backed list:
@Override protected
List<Integer> initialize(int size) {
Integer[] ia = Generated.array(Integer.class,
new CountingSupplier.Integer(), size);
Integer[] ia = new Integer[size];
Arrays.setAll(ia, new Count.Integer()::get);
return Arrays.asList(ia);
}
};

View File

@ -2,7 +2,7 @@
// (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.
// Sorting and searching Lists with Collections utilities.
// Sorting and searching Lists with Collections utilities
import java.util.*;
public class ListSortSearch {
@ -28,7 +28,8 @@ public class ListSortSearch {
"Location of " + key + " is " + index +
", list.get(" + index + ") = " + list.get(index));
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);
index = Collections.binarySearch(list, key,
String.CASE_INSENSITIVE_ORDER);

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