您的位置:首页 > 编程语言 > Java开发

Java-Java编程思想第四版 第十六章 数组 练习

2018-04-04 16:22 633 查看
练习1:// arrays/Ex1.java
// TIJ4 Chapter Arrays, Exercise 1, page 752
/* Create a method that takes an array of Pet as an argument.
* Call the method, creating the argument dynamically. Demonstrate that
* ordinary aggregate array intitialization doesn't work in this case.
* Discover the only situations where ordinary aggregate array initialization
* works, and where dynamic aggregate array initialization is redundant.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import typeinfo.pets.*;
class A { public String toString() { return "A Object"; } }

public class Ja16_1 {
// Method that takes Pet[] as argument
// and prints the argument as array elements and as List or String:
public static void test(Pet[] a) {
print(Arrays.asList(a));
}
// Generic version:
public static <T> void test(T[] t) {
print(Arrays.asList(t));
}
// int version:
public static void test(int[] ia) {
print(Arrays.toString(ia));
}

public static void main(String[] args) {
print("For objects, e.g., Pets:");
// Array is created and initialized (aggregate initialization)
// but all elements are null, not Pets:
test(new Pet[3]);
// Dynamic aggregate initialization works;
// elements are now Pets:
test(new Pet[]{
new Pet(), new Pet() });
// Aggregate initialization this way works:
Pet[] a = { new Pet(),
new Pet(), new Pet() };
test(a);
// Elements initialized to null:
Pet[] bsa = new Pet[2];
test(bsa);
bsa = a;
test(bsa);
print("-------------");
print("For primitives, e.g., int:");
// Dynamic aggregate initialization works:
test(new int[]{ new Integer(0), new Integer(0) });
// But may be considered redundant, since
// aggregate initialization works:
// elements initialized to zero (not null):
test(new int[2]);
// Ordinary aggregate initialization this way also works:
int[] ia = { 1, 2, 3, };
test(ia);
}
}


练习2:
// Write a method that takes an int argument and returns an
// array of that size filled BerylliumSpheres.
import typeinfo.pets.*;
import java.util.*;
import static net.mindview.util.Print.*;
class A{
private static final Pet[] pp={new Dog(),new Cat(),new Pug()};
static Pet[] p(int i){
boolean[] b=new boolean[i];
Pet[] pet=new Pet[i];
Random rand=new Random(22);
int t=0;
for(int j=0;j<i;j++){
do
t=rand.nextInt(pet.length);
while(b[t]);
pet[j]=pp[t];
}
return pet;
}
}
public class Ja16_2{
public static void main(String[] args) {
print(Arrays.toString(A.p(2)));
}

}

练习3:
/* Write a method that creates and initializes a two-dimensional array of double.
* The size of the array is determined by the * arguments of the method, and the
* initialization values are a range determined by beginning and ending values
* that are also arguments of the method. Create a second method that will print
* the array generated by the first method. In main() test the methods by
* creating and printing several different sizes of arrays.
*/
import static net.mindview.util.Print.*;
import java.util.*;
class A{
double[][] f(int size1,int size2,double start, double end){
double[][] d=new double[size1][size2];
for(int i=0;i<size1;i++)
for(int j=0;j<size2;j++)
d[i][j]=start +((double)j/(size2 - 1))*(((double)j + (double)i)/(size2 - 1 + i))*(end - start);
return d;
}
void g(int size1,int size2,double start, double end){print(Arrays.deepToString(f(size1,size2,start,end)));}
}
public class Ja16_3{
public static void main(String[] args) {
A a=new A();
a.g(2,4,3,19);
}
}

练习4:
// Repeat the previous exercise for a three-dimensional array.
import static net.mindview.util.Print.*;
import java.util.*;
class A{
double[][] f(int size1,int size2,double start, double end){
double[][] d=new double[size1][size2];
for(int i=0;i<size1;i++)
for(int j=0;j<size2;j++)
d[i][j]=start +((double)j/(size2 - 1))*(((double)j + (double)i)/(size2 - 1 + i))*(end - start);
return d;
}
void g(int size1,int size2,double start, double end){print(Arrays.deepToString(f(size1,size2,start,end)));}
}
public class Ja16_3{
public static void main(String[] args) {
A a=new A();
a.g(2,4,3,19);
}
}

练习5:
// Demonstrate that multidimensional arrays of non-primitives are
// automatically initialized to null.
import static net.mindview.util.Print.*;
import java.util.*;
class A{
double[][] f(int size1,int size2,double start, double end){
double[][] d=new double[size1][size2];

return d;
}
void g(int size1,int size2,double start, double end){print(Arrays.deepToString(f(size1,size2,start,end)));}
}
public class Ja16_5{
public static void main(String[] args) {
A a=new A();
a.g(2,4,3,19);
}
}


练习6:

练习7:

练习8:
// Demonstrate the assertions in the previous paragraph.
import static net.mindview.util.Print.*;
public class Ja16_8{
public static void main(String[] args){
Object[] o=new Object[]{new String("fsd"),new Integer(23)};
print(o[0].getClass());
print(o[1].getClass());

}
}

练习9:

练习10:

练习11:
// Show that autoboxing doesn't work with arrays.
import java.util.*;
import static net.mindview.util.Print.*;
public class Ja16_11{
public static void main(String[] args){
Integer[] a=new Integer[]{1,2,4,6};
print(Arrays.toString(a));
//int[] b=a;
}
}

练习12:
// Create an initialized array of double using CountingGenerator.
// Print the results.
import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.util.*;
public class Ja16_12{
public static void main(String[] args){
print(Arrays.toString(Generated.array(Double.class,new CountingGenerator.Double(),5)));
}
}

练习13:
// Fill a String using CountingGenerator.Character.

import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.util.*;

public class Ja16_13{
public static void main(String[] args){
Character[] ca=Generated.array(Character.class,new CountingGenerator.Character(),5);
char[] caa=ConvertTo.primitive(ca);
String a=new String(caa);
print(a);
}
}

练习14:// Create an array of each primitive type, then fill each array by using
// CountingGenerator. Print each array.
import net.mindview.util.*;
import static net.mindview.util.Print.*;
import java.util.*;

public class Ja16_14{
public static void main(String[] args){
CountingGenerator.Double cd=new CountingGenerator.Double();
Double[] d=new Double[5];
for(int i=0;i<d.length;i++){
d[i]=cd.next();
}
print(Arrays.toString(d));
}
}

练习15:
// Modify ContainerComparison.java by creating a net.mindview.util.Generator for
// BerylliumSphere, and change main() to use that net.mindview.util.Generator
// with Generated.array().
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
//interface net.mindview.util.Generator<T> { T next(); } ///:~
/*class Generated {
// Fill an existing array:
public static <T> T[] array(T[] a, net.mindview.util.Generator<T> gen) {
return new CollectionData<T>(gen, a.length).toArray(a);
}
// Create a new array:
@SuppressWarnings("unchecked")
public static <T> T[] array(Class<T> type,
net.mindview.util.Generator<T> gen, int size) {
T[] a =
(T[])java.lang.reflect.Array.newInstance(type, size);
return new CollectionData<T>(gen, size).toArray(a);
}
}*/
class BerylliumSphere {
private static long counter;
private final long id = counter++;
public String toString() { return "Sphere " + id; }

static class generator implements net.mindview.util.Generator<BerylliumSphere>{
public BerylliumSphere next(){
return new BerylliumSphere();
}
}
}

public class Ja16_15 {
public static void main(String[] args) {
print(Arrays.toString(Generated.array(BerylliumSphere.class,new BerylliumSphere.generator(),5)));

}
}
//Gener
4000
ator需要用全限定名net.mindview.util.GeneratorPS:Generator需要用全限定名net.mindview.util.Generator
练习16:
/* Starting with CountingGenerator.java, create a SkipGenerator class
* that produces new values by incrementing according to a constructor
* argument. Modify TestArrayGeneration.java to show that your new
* class works correctly.
*/

import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
class CountingGenerator{
public static class
Boolean implements Generator<java.lang.Boolean> {
private boolean value = false;
public java.lang.Boolean next() {
value = !value; // Just flips back and forth
return value;
}
public java.lang.Boolean next(int n) {
value = !value; // Just flips back and forth
return value;
}
}
public static class
Byte implements Generator<java.lang.Byte> {
private byte value = 0;
public java.lang.Byte next() { return value++; }
public java.lang.Byte next(int n) { return value+=n; }
}
static char[] chars = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
public static class
Character implements Generator<java.lang.Character> {
int index = -1;
public java.lang.Character next() {
index = (index + 1) % chars.length;
return chars[index];
}
public java.lang.Character next(int n) {
index = (index + n) % chars.length;
return chars[index];
}
}
public static class
String implements Generator<java.lang.String> {
private int length = 7;
Generator<java.lang.Character> cg = new Character();
public String() {}
public String(int length) { this.length = length; }
public java.lang.String next() {
char[] buf = new char[length];
for(int i = 0; i < length; i++)
buf[i] = cg.next();
return new java.lang.String(buf);
}
/*public java.lang.String next(int n) {
char[] buf = new char[length];
for(int i = 0; i < length; i++)
buf[i] = cg.next(n);
return new java.lang.String(buf);
}*/
}
public static class
Short implements Generator<java.lang.Short> {
private short value = 0;
public java.lang.Short next() { return value++; }
public java.lang.Short next(int n) { return value+=n; }
}
public static class
Integer implements Generator<java.lang.Integer> {
private int value = 0;
public java.lang.Integer next() { return value++; }
public java.lang.Integer next(int n) { return value+=n; }
}
public static class
Long implements Generator<java.lang.Long> {
private long value = 0;
public java.lang.Long next() { return value++; }
public java.lang.Long next(int n) { return value+=n; }
}
public static class
Float implements Generator<java.lang.Float> {
private float value = 0;
public java.lang.Float next() {
float result = value;
value += 1.0;
return result;
}
public java.lang.Float next(float n) {
float result = value;
value += n;
return result;
}
}
public static class
Double implements Generator<java.lang.Double> {
private double value = 0.0;
public java.lang.Double next() {
double result = value;
value += 1.0;
return result;
}
public java.lang.Double next(double n) {
double result = value;
value += n;
return result;
}
}
} ///:~
public class Ja16_16{

public static void main(String[] args){
CountingGenerator.Double cd=new CountingGenerator.Double();
print(cd.next((double)5.0));
print(cd.next((double)5.0));
}
}

练习17:
// Create and test a Generator for BigDecimal, and ensure
// that it works with the Generated methods.
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.*;
import java.math.*;
class BigDecimalGenerator implements net.mindview.util.Generator<BigDecimal>{
private BigDecimal bd=new BigDecimal(0.0);
public BigDecimal next(){
return bd=bd.add(new BigDecimal(1.0));
}
}
public class Ja16_17{
public static void main(String[] args){
print(Arrays.toString(Generated.array(BigDecimal.class,new BigDecimalGenerator(),4)));
}
}

练习18:
// Create and fill and array of BerylliumSphere. Copy this array
// to a new array and show that it's a shallow copy.
import java.util.*;
import typeinfo.pets.*;
import static net.mindview.util.Print.*;
public class Ja16_18{
public static void main(String[] args) {
Pet[] p=new Pet[]{new Cat(),new Dog(),new Pug()};
Pet[] m=new Pet[]{new Pet(),new Pet(),new Pet()};
System.arraycopy(p,0,m,0,p.length);
print(Arrays.toString(p));
print(Arrays.toString(m));
}
}

练习19:
/* Create a class with an int field that's initialized from a constructor
* argument. Create two arrays of these objects, using identical
* intitialization values for each array, and show that Arrays.equals() says
* that they are unequal. Add an equals() method to your class to fix the
* problem.
*/
import java.util.*;

import static net.mindview.util.Print.*;
class A{
public int n;
A(int n){this.n=n;}
public boolean equals(Object b){
if(b.getClass().getSimpleName()=="A")return (((A)b).n==this.n) ;
return false;
}
}
public class Ja16_19{
public static void main(String[] args){

A[] a={new A(1)};
A[] b={new A(1)};
print(Arrays.equals(a,b));
}
}

练习20:
// Demonstrate deepEquals() for multidimensional arrays.
import java.util.*;

import static net.mindview.util.Print.*;
public class Ja16_20{
public static void main(String[] args){
int[][][] a={{{2,3},{5,7}},{{3,7,9},{7,9,2},{5}}};
int[][][] b={{{2,3},{5,7}},{{3,7,9},{7,9,2},{5}}};
print(Arrays.deepEquals(a,b));
}
}

练习21:
// Try to sort an array of the objects in Exercise 18. Implement
// Comparable to fix the problem. Now create a Comparator to sort
import java.util.*;
import typeinfo.pets.*;
import static net.mindview.util.Print.*;
class CompBerylliumSphere
implements Comparable<CompBerylliumSphere> {
private static long count;
protected final long id = count++;
public int compareTo(CompBerylliumSphere c2) {
return (this.id < c2.id ? -1 : (this.id == c2.id ? 0 : 1));
}

public String toString() {
return "BerylliumSphere " + id;
}
}
class AComparator implements Comparator<CompBerylliumSphere>{
public int compare(CompBerylliumSphere c1, CompBerylliumSphere c2){
return (c2.id<c1.id?-1:(c2.id==c1.id?0:1));
}
}
public class Ja16_21{
public static void main(String[] args) {
CompBerylliumSphere[] m=new CompBerylliumSphere[]{new CompBerylliumSphere(),new CompBerylliumSphere(),new CompBerylliumSphere()};
Arrays.sort(m,new AComparator());
print(Arrays.toString(m));
}
}

练习22:
// Show that the results of performing a binarySearch() on an
// unsorted array are unpredictable.
import java.util.*;
import typeinfo.pets.*;
import static net.mindview.util.Print.*;
class CompBerylliumSphere
implements Comparable<CompBerylliumSphere> {
private static long count;
protected final long id = count++;
public int compareTo(CompBerylliumSphere c2) {
return (this.id < c2.id ? -1 : (this.id == c2.id ? 0 : 1));
}

public String toString() {
return "BerylliumSphere " + id;
}
}
class AComparator implements Comparator<CompBerylliumSphere>{
public int compare(CompBerylliumSphere c1, CompBerylliumSphere c2){
return (c2.id<c1.id?-1:(c2.id==c1.id?0:1));
}
}
public class Ja16_22{
public static void main(String[] args) {
CompBerylliumSphere c=new CompBerylliumSphere();
CompBerylliumSphere[] m=new CompBerylliumSphere[]{new CompBerylliumSphere(),new CompBerylliumSphere(),new CompBerylliumSphere(),new CompBerylliumSphere(),c,new CompBerylliumSphere(),new CompBerylliumSphere()};
//Arrays.sort(m,new AComparator());
print(Arrays.binarySearch(m,c/*,new AComparator()*/));
print(Arrays.toString(m));
}
}
/*-1
[BerylliumSphere 1, BerylliumSphere 2, BerylliumSphere 3, BerylliumSphere 4, BerylliumSphere 0, Beryllium
Sphere 5, BerylliumSphere 6]*/

练习23:
// Create an array of Integer fill it with random int values (using
// autoboxing), and sort it into reverse order using a Comparator.
import net.mindview.util.*;
import java.util.*;
import static net.mindview.util.Print.*;
public class Ja16_23{
public static void main(String[] args) {
Integer[] ig=new Integer[5];
Generated.array(ig,new RandomGenerator.Integer());
Arrays.sort(ig,Collections.reverseOrder());
print(Arrays.toString(ig));
}
}

练习24:
// Show that the class from Exercise 19 can be searched.
import java.util.*;
import static net.mindview.util.Print.*;
class A implements Comparable<A>{
public int n;
A(int n){this.n=n;}
public boolean equals(Object b){
if(b.getClass().getSimpleName()=="A")return (((A)b).n==this.n) ;
return false;
}
public int compareTo(A rv){
return (this.n<rv.n?-1:(this.n==rv.n?0:1));
}
}
public class Ja16_24{
public static void main(String[] args){
A mm=new A(5);
A[] a={new A(1),new A(3),mm,new A(5),new A(7)};
//A[] b={new A(1)};
//print(Arrays.equals(a,b));
Arrays.sort(a);
print(Arrays.binarySearch(a,mm));
}
}

练习25:
// Rewrite PythonLists.py in Java.
import java.util.*;
import static net.mindview.util.Print.*;
class Mylist{
List<Integer> ls=new ArrayList<Integer>();
Mylist(List<Integer> ls){
this.ls=ls;
}
List<Integer> rls=new ArrayList<Integer>();
List<Integer> getReversed(){
ListIterator lit=ls.listIterator(ls.size());
while(lit.hasPrevious()){
rls.add((Integer)lit.previous());
}
return rls;
}
}
public class Ja16_25{
public static void main(String[] args){
List<Integer> ls=new ArrayList<Integer>(Arrays.asList(1,3,5,7,3));
Mylist ml=new Mylist(ls);
print(ml.getReversed());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: