Thinking in Java第四版Acess部分答案
(完整版)JAVA编程思想(第四版)课后答案

Java编程思想(第四版)习题答案第二章练习1:public class PrimitiveTest {static int i;static char c;public static void main(String[] args) {System.out.println("int = " + i);System.out.println("char = " + c);}}练习2:public class HelloWorld {public static void main(String[] args) {System.out.println("Hello World!");}}练习3:public class ATNTest {public static void main(String[] args) {class ATypeName {int i;double d;boolean b;void show() {System.out.println(i);System.out.println(d);System.out.println(b);}}A TypeName a = new ATypeName();a.i = 3;a.d = 2.71828;a.b = false;a.show();}}练习4:public class DataOnlyTest {public static void main(String[] args) {class DataOnly {int i;double d;boolean b;void show() {System.out.println(i);System.out.println(d);System.out.println(b);}}DataOnly data = new DataOnly();data.i = 3;data.d = 2.71828;data.b = false;data.show();}}练习5:public class DOTest2 {public static void main(String[] args) {class DataOnly {int i;double d;boolean b;void show() {System.out.println(i);System.out.println(d);System.out.println(b);}}DataOnly data = new DataOnly();data.i = 234;data.d = 2.1234545;data.b = true;data.show();}}练习6:public class StorageTest {public static void main(String[] args) {class StoreStuff {int storage(String s) {return s.length() * 2;}}StoreStuff x = new StoreStuff();System.out.println(x.storage("hi"));}}练习7:class StaticTest {static int i = 47;}class Incrementable {static void increment() { StaticTest.i++; }}public class ITest {public static void main(String[] args) {System.out.println("StaticTest.i= " + StaticTest.i);StaticTest st1 = new StaticTest();StaticTest st2 = new StaticTest();System.out.println("st1.i= " + st1.i);System.out.println("st2.i= " + st2.i);Incrementable sf = new Incrementable();sf.increment();System.out.println("After sf.increment() called: ");System.out.println("st1.i = " + st1.i);System.out.println("st2.i = " + st2.i);Incrementable.increment();System.out.println("After Incrementable.increment called: ");System.out.println("st1.i = " + st1.i);System.out.println("st2.i = " + st2.i);}}练习8:class StaticTest {static int i = 47;}class Incrementable {static void increment() { StaticTest.i++; }}public class OneStaticTest {public static void main(String[] args) {System.out.println("StaticTest.i= " + StaticTest.i);StaticTest st1 = new StaticTest();StaticTest st2 = new StaticTest();System.out.println("st1.i= " + st1.i);System.out.println("st2.i= " + st2.i);Incrementable.increment();System.out.println("After Incrementable.increment() called: ");System.out.println("st1.i = " + st1.i);System.out.println("st2.i = " + st2.i);Incrementable.increment();System.out.println("After Incrementable.increment called: ");System.out.println("st1.i = " + st1.i);System.out.println("st2.i = " + st2.i);st1.i = 3;System.out.println("After st1.i = 3, ");System.out.println("st1.i = " + st1.i);System.out.println("st2.i = " + st2.i);System.out.println("Create another StaticTest, st3.");StaticTest st3 = new StaticTest();System.out.println("st3.i = " + st3.i);}}练习9:public class AutoboxTest {public static void main(String[] args) {boolean b = false;char c = 'x';byte t = 8;short s = 16;int i = 32;long l = 64;float f = 0.32f;double d = 0.64;Boolean B = b;System.out.println("boolean b = " + b);System.out.println("Boolean B = " + B);Character C = c;System.out.println("char c = " + c);System.out.println("Character C = " + C);Byte T = t;System.out.println("byte t = " + t);System.out.println("Byte T = " + T);Short S = s;System.out.println("short s = " + s);System.out.println("Short S = " + S);Integer I = i;System.out.println("int i = " + i);System.out.println("Integer I = " + I);Long L = l;System.out.println("long l = " + l);System.out.println("Long L = " + L);Float F = f;System.out.println("float f = " + f);System.out.println("Float F = " + F);Double D = d;System.out.println("double d = " + d);System.out.println("Double D = " + D);}}练习10:public class CommandArgTest {public static void main(String[] args) {int[]args1={1,2,3};System.out.println("args[0] = " + args1[0]);System.out.println("args[1] = " + args1[1]);System.out.println("args[2] = " + args1[2]);}}练习11:public class Rainbow {public static void main(String[] args) {AllTheColorsOfTheRainbow atc = new AllTheColorsOfTheRainbow();System.out.println("atc.anIntegerRepresentingColors = " + atc.anIntegerRepresentingColors);atc.changeColor(7);atc.changeTheHueOfTheColor(77);System.out.println("After color change, atc.anIntegerRepresentingColors = " + atc.anIntegerRepresentingColors);System.out.println("atc.hue = " + atc.hue);}}class AllTheColorsOfTheRainbow {int anIntegerRepresentingColors = 0;int hue = 0;void changeTheHueOfTheColor(int newHue) {hue = newHue;}int changeColor(int newColor) {return anIntegerRepresentingColors = newColor;}}练习12:public class DocTest {/** Entry poing to class & application.* @param args array of string arguments* @throws exceptions No exceptions thrown*/public static void main(String[] args) {System.out.println("Hello, it's: ");System.out.println(new Date());}}练习13-1:public class Documentation1 {/** A field comment */public int i;/** A method comment */public void f() {}}2:public class Documentation2 {Date d = new Date();void showDate() {System.out.println("Date = " + d);}}3:public class Documentation3 {public static void main(String[] args) {Date d = new Date();System.out.println("d = " + d);}}练习14:public class Documentation4 {public int i = 2;private int j = 3;public static void main(String[] args) {Date d = new Date();System.out.println("d = " + d);}}练习15:public class HelloDocTest {public static void main(String[] args) {System.out.println("Hello World!");}}练习16:class Tree {int height;Tree() {System.out.println("Planting a seedling");height = 0;}Tree(int initialHeight) {height = initialHeight;System.out.println("Creating new tree that is " + height + " feet tall");}void info() {System.out.println("Tree is " + height + " feet tall");}void info(String s) {System.out.println(s + ": Tree is " + height + " feet tall"); }}public class Overloading {public static void main(String[] args) {for(int i = 0; i < 5; i++) {Tree t = new Tree(i);();("overloading method");}// Overloaded constructor:new Tree();}}第三章练习1:public class PrintTest {public static void main(String[] args) {print("Hello, from short form.");P.rintln("Hello from greggordon form.");System.out.println("Hello from long form.");}}练习2:class Tube {float level;}public class Assign {public static void main(String[] args) {Tube t1 = new Tube();Tube t2 = new Tube();t1.level = 0.9f;t2.level = 0.47f;P.rintln("1: t1.level: " + t1.level + ", t2.level: " + t2.level);t1 = t2;P.rintln("2: t1.level: " + t1.level + ", t2.level: " + t2.level);t1.level = 0.27f;P.rintln("3: t1.level: " + t1.level + ", t2.level: " + t2.level);}}练习3:class Box {float a;}public class PassObject2 {static void f(Box y) {y.a = 2.71828f;}public static void main(String[] args) {Box x = new Box();x.a = 3.1416f;print("1: x.a = " + x.a);f(x);print("2: x.a = " + x.a);}}练习4:class VelocityCalculator {static float velocity (float d, float t) {if(t == 0) return 0f;else return d/t;}}public class VelocityTester {public static void main(String[] args) {float d = 565.3f;float t = 3.6f;System.out.println("Distance: " + d);System.out.println("Time: " + t);float v = VelocityCalculator.velocity(d, t);System.out.println("Velocity: " + v);}}练习5:class Dog {String name;String says;void setName(String n) {name = n;}void setSays(String s) {says = s;}void showName() {P.rintln(name);}void speak() {P.rintln(says);}}public class DogTest {public static void main(String[] args) {Dog spot = new Dog();spot.setName("Spot");spot.setSays("Ruff!");Dog scruffy = new Dog();scruffy.setName("Scruffy");scruffy.setSays("Wurf!");spot.showName();spot.speak();scruffy.showName();scruffy.speak();}}练习6:class Dog {String name;String says;void setName(String n) {name = n;}void setSays(String s) {says = s;}void showName() {P.rintln(name);}void speak() {P.rintln(says);}}public class DogCompare {public static void main(String[] args) {Dog spot = new Dog();spot.setName("Spot");spot.setSays("Ruff!");Dog scruffy = new Dog();scruffy.setName("Scruffy");scruffy.setSays("Wurf!");spot.showName();spot.speak();scruffy.showName();scruffy.speak();Dog butch = new Dog();butch.setName("Butch");butch.setSays("Hello!");butch.showName();butch.speak();P.rintln("Comparison: ");P.rintln("spot == butch: " + (spot == butch));P.rintln("spot.equals(butch): " + spot.equals(butch));P.rintln("butch.equals(spot): " + butch.equals(spot));P.rintln("Now assign: spot = butch");spot = butch;P.rintln("Compare again: ");P.rintln("spot == butch: " + (spot == butch));P.rintln("spot.equals(butch): " + spot.equals(butch));P.rintln("butch.equals(spot): " + butch.equals(spot));P.rintln("Spot: ");spot.showName();spot.speak();P.rintln("Butch: ");butch.showName();butch.speak();}}练习7:。
thinking injava习题答案1

这是第2章的答案:Exercise 1//: c02:E01_HelloWorld.java//+M java E01_HelloWorld/****************** Exercise 1 ******************* Following the HelloDate.java example in this* chapter, create a "hello, world" program that* simply prints out that statement. You need* only a single method in your class (the "main"* one that gets executed when the program* starts). Remember to make it static and to* include the argument list, even though you* don't use the argument list. Compile the* program with javac and run it using java. If* you are using a different development* environment than the JDK, learn how to compile* and run programs in that environment.***********************************************/public class E01_HelloWorld {public static void main(String args[]) {System.out.println("Hello, world!");}} ///:~The +M directive tells my makefile builder tool to add this command (java HelloWorld) to the commands that it automatically runs while building the program. This way, if the execution fails for any reason then the make will abort and show that something is wrong for a particular program. This is a very simple form of built-in testing: automatically running the program to ensure no exceptions are thrown. You’ll see this on most of the programs in this solution guide, and the makefiles that come with the source code (that is packaged with this guide) will automatically run the programs.Exercise 2//: c02:E02_ATypeName.java//+M java E02_ATypeName/****************** Exercise 2 ******************* Find the code fragments involving ATypeName* and turn them into a program that compiles and * runs.***********************************************/ public class E02_ATypeName {public static void main(String args[]) {E02_ATypeName a = new E02_ATypeName();}} ///:~Exercise 3//: c02:E03_DataOnly.java//+M java E03_DataOnly/****************** Exercise 3 ****************** * Turn the DataOnly code fragments into a* program that compiles and runs.***********************************************/ public class E03_DataOnly {int i;float f;boolean b;public static void main(String[] args) {E03_DataOnly d = new E03_DataOnly();d.i = 47;d.f = 1.1f;d.b = false;}} ///:~Exercise 4//: c02:E04_DataOnly2.java//+M java E04_DataOnly2/****************** Exercise 4 ****************** * Modify Exercise 3 so that the values of the* data in DataOnly are assigned to and printed * in main().***********************************************/ public class E04_DataOnly2 {int i;float f;boolean b;public static void main(String[] args) {E04_DataOnly2 d = new E04_DataOnly2();d.i = 47;System.out.println("d.i = " + d.i);d.f = 1.1f;System.out.println("d.f = " + d.f);d.b = false;System.out.println("d.b = " + d.b);}} ///:~Exercise 5//: c02:E05_Storage.java//+M java E05_Storage/****************** Exercise 5 ******************* Write a program that includes and calls the* storage() method defined as a code fragment in* this chapter.***********************************************/public class E05_Storage {String s = "Hello, World!";int storage(String s) {return s.length() * 2;}void print() {System.out.println("storage(s) = " + storage(s));}public static void main(String[] args) {E05_Storage st = new E05_Storage();st.print();}} ///:~You could have also made storage( ) a static method and just called it from main( ).Exercise 6//: c02:E06_StaticFun.java//+M java E06_StaticFun/****************** Exercise 6 ******************* Turn the StaticFun code fragments into a* working program.***********************************************/class StaticTest {static int i = 47;}public class E06_StaticFun {static void incr() { StaticTest.i++; }public static void main(String[] args) {E06_StaticFun sf = new E06_StaticFun();sf.incr();E06_StaticFun.incr();}} ///:~Exercise 7//: c02:E07_ShowArgs.java//+M java E07_ShowArgs A B C/****************** Exercise 7 ******************* Write a program that prints three arguments* taken from the command line. To do this,* you'll need to index into the command-line* array of Strings.***********************************************/public class E07_ShowArgs {public static void main(String[] args) {System.out.println(args[0]);System.out.println(args[1]);System.out.println(args[2]);}} ///:~Note that you’ll get a run-time exception if you run the program without enough arguments. You should actually test for the length of the array first, like this://: c02:E07_ShowArgs2.java//+M java E07_ShowArgs2 A B C/****************** Exercise 7 ******************* Testing for the length of the array first.***********************************************/public class E07_ShowArgs2 {public static void main(String[] args) {if(args.length < 3) {System.out.println("Need 3 arguments");System.exit(1);}System.out.println(args[0]);System.out.println(args[1]);System.out.println(args[2]);}} ///:~The System.exit( ) call terminates the program and passes its argument back to the operating system as a result (with most operating systems, a non-zero result indicates that the program execution failed).Exercise 8//: c02:E08_AllTheColorsOfTheRainbow.java//+M java E08_AllTheColorsOfTheRainbow/****************** Exercise 8 ******************* Turn the AllTheColorsOfTheRainbow example into* a program that compiles and runs.***********************************************/public class E08_AllTheColorsOfTheRainbow {int anIntegerRepresentingColors;void changeTheHueOfTheColor(int newHue) {anIntegerRepresentingColors = newHue;}public static void main(String[] args) {E08_AllTheColorsOfTheRainbow all =new E08_AllTheColorsOfTheRainbow();all.changeTheHueOfTheColor(27);}} ///:~Exercise 9//: c02:E09_HelloDate.java//+M java E09_HelloDate//+M mkdir HelloDate//+M javadoc E09_HelloDate.java –d HelloDate/****************** Exercise 9 ******************* Find the code for the second version of* HelloDate.java, which is the simple comment* documentation example. Execute javadoc on the* file and view the results with your Web* browser.***********************************************/import java.util.*;/** The first Thinking in Java example program.* Displays a string and today's date.* @author Bruce Eckel* @author * @version 2.0*/public class E09_HelloDate {/** Sole entry point to class & application* @param args array of string arguments* @return No return value* @exception exceptions No exceptions thrown*/public static void main(String[] args) {System.out.println("Hello, it's: ");System.out.println(new Date());}} ///:~The command to run javadoc on the file and to place the results in a separate subdirectory called HelloDate is embedded as the third +M comment directive above. Note that javadoc doesn’t automatically create the destination directory.Exercise 10//: c02:E10_docTest.java//+M mkdir docTest//+M javadoc E10_docTest.java –d docTest/****************** Exercise 10 ****************** Turn docTest into a file that compiles and* then run it through javadoc. Verify the* resulting documentation with your Web browser.***********************************************//** A class comment */public class E10_docTest {/** A variable comment */public int i;/** A method comment */public void f() {}} ///:~You must still execute javadoc and verify the results, but you can see the commands that are added to the makefile to do this, as +M comment directives. Note that we’re only concerned that the file compiles, so there’s no makefile directive to run it.Exercise 11//: c02:E11_docTest2.java//+M mkdir docTest2//+M javadoc E11_docTest2.java –d docTest2/****************** Exercise 11 ****************** Add an HTML list of items to the documentation* in Exercise 10.***********************************************//** A class comment* <pre>* System.out.println(new Date());* </pre>*/public class E11_docTest2 {/** A variable comment */public int i;/** A method comment* You can <em>even</em> insert a list:* <ol>* <li> Item one* <li> Item two* <li> Item three* </ol>*/public void f() {}} ///:~I simply added the HTML code fragments from the chapter examples. You must still execute javadoc and verify the results, but you can see the commands that are added to the makefile to do this, as +M comment directives.Exercise 12//: c02:E12_HelloWorldDoc.java//+M java E12_HelloWorldDoc//+M mkdir HelloWorldDoc//+M javadoc E12_HelloWorldDoc.java –d HelloWorldDoc/****************** Exercise 12 ****************** Take the program in Exercise 1 and add comment* documentation to it. Extract this comment* documentation into an HTML file using javadoc* and view it with your Web browser.***********************************************//** A first example from <I>Thinking in Java,* 2nd edition</I>. Demonstrates the basic class* structure and the creation of a* <code>main()</code> function.*/public class E12_HelloWorldDoc {/** The <code>main()</code> function which iscalled when the program is executed by saying<code>java E12_HelloWorldDoc</code>.@param args array passed from the command-line*/public static void main(String args[]) {System.out.println("Hello, world!");}} ///:~You must still execute javadoc and verify the results, but you can see the commands that are added to the makefile to do this, as +M comment directives.。
thinking in java习题答案

thinking in java习题答案Thinking in Java习题答案在学习编程语言Java的过程中,练习习题是非常重要的一部分。
通过解答习题,我们可以加深对Java语言的理解,巩固所学知识,并且提高编程能力。
本文将为大家提供一些Thinking in Java习题的答案,希望能够帮助大家更好地学习和掌握Java编程。
1. 以下是一个简单的Java程序,输出结果是什么?```javapublic class Test {public static void main(String[] args) {int a = 5;int b = 10;System.out.println("a + b = " + a + b);}}```答案:输出结果是"a + b = 510"。
这是因为在Java中,"+"操作符在遇到字符串时会进行字符串连接操作,而不是数值相加。
因此,a和b会被当做字符串连接,而不是数值相加。
2. 以下是一个Java程序,输出结果是什么?```javapublic class Test {public static void main(String[] args) {int a = 5;int b = 10;System.out.println("a + b = " + (a + b));}}```答案:输出结果是"a + b = 15"。
这是因为在这个程序中,我们使用了小括号将a + b括起来,这样就会先进行数值相加操作,然后再进行字符串连接操作。
3. 以下是一个Java程序,输出结果是什么?```javapublic class Test {public static void main(String[] args) {String s = "Hello";s = s + " World";System.out.println(s);}}```答案:输出结果是"Hello World"。
java编程思想 第四版 习题答案

java编程思想第四版习题答案Java编程思想是一本经典的Java编程教材,它深入浅出地介绍了Java编程的基本原理和思想。
为了更好地理解和掌握这本书,我特意整理了第四版习题的答案,并在实践中验证了这些答案的正确性。
在第一章中,书中提到了Java编程的基本思想和概念。
习题一要求我们解释Java程序的编译和执行过程。
编译过程是将Java源代码转换成字节码的过程,而执行过程是虚拟机将字节码转换成机器码并执行的过程。
这两个过程是相互独立的,编译过程只需要一次,而执行过程可以多次进行。
习题二要求我们解释Java中的关键字和标识符的概念。
关键字是Java语言中预先定义的具有特殊含义的单词,如class、public、static等。
而标识符是由程序员自定义的用来表示变量、方法、类等的名称,标识符要符合一定的命名规则,如不能以数字开头,不能包含特殊字符等。
在第二章中,书中介绍了Java中的数据类型和运算符。
习题一要求我们解释Java中的基本数据类型和引用数据类型的区别。
基本数据类型是Java语言中预先定义的数据类型,如int、float、boolean等,它们的值直接存储在变量中。
而引用数据类型是由程序员自定义的数据类型,如类、接口等,它们的值存储在堆内存中,变量中只存储引用地址。
习题二要求我们解释Java中的赋值运算符和逻辑运算符。
赋值运算符用于将一个值赋给一个变量,如a = 10;逻辑运算符用于对多个条件进行逻辑判断,如&&表示与运算,||表示或运算。
在第三章中,书中介绍了Java中的控制流程和数组。
习题一要求我们解释Java中的if语句和switch语句的用法。
if语句用于根据条件判断是否执行某段代码,而switch语句用于根据不同的值选择执行不同的代码块。
习题二要求我们解释Java中的for循环和while循环的用法。
for循环用于重复执行一段代码,可以指定循环的初始条件、循环条件和循环步长;而while循环用于当满足某个条件时重复执行一段代码,循环条件在循环开始前判断。
java第四版课后习题答案

java第四版课后习题答案Java第四版课后习题答案Java是一种广泛应用于软件开发领域的编程语言,具有跨平台、面向对象等特点。
对于学习Java的人来说,课后习题是巩固知识、提高编程能力的重要方式。
本文将为读者提供Java第四版课后习题的答案,帮助读者更好地理解和掌握Java编程。
一、基础知识1. 什么是Java虚拟机(JVM)?它的作用是什么?答:Java虚拟机(JVM)是Java程序运行的环境,它负责将Java源代码编译成字节码,并在不同的操作系统上运行。
JVM的作用是实现Java的跨平台特性,使得Java程序可以在不同的操作系统上运行。
2. Java中的八种基本数据类型是什么?答:Java中的八种基本数据类型分别是byte、short、int、long、float、double、char和boolean。
3. 什么是面向对象编程(OOP)?Java是一种面向对象的编程语言吗?答:面向对象编程(OOP)是一种编程范式,通过将数据和方法封装在对象中,以对象为中心进行程序设计和开发。
Java是一种面向对象的编程语言,它支持封装、继承和多态等面向对象的特性。
二、控制流程1. Java中的条件语句有哪些?答:Java中的条件语句包括if语句、switch语句和三元运算符。
2. Java中的循环语句有哪些?答:Java中的循环语句包括for循环、while循环和do-while循环。
3. 如何在循环中使用break和continue语句?答:break语句用于立即终止循环,跳出循环体。
continue语句用于跳过当前循环的剩余代码,继续下一次循环。
三、数组和集合1. 如何声明和初始化一个一维数组?答:可以使用以下方式声明和初始化一个一维数组:```int[] array = new int[5]; //声明一个长度为5的整型数组int[] array = {1, 2, 3, 4, 5}; //声明并初始化一个整型数组```2. 如何声明和初始化一个二维数组?答:可以使用以下方式声明和初始化一个二维数组:```int[][] array = new int[3][2]; //声明一个3行2列的整型二维数组int[][] array = {{1, 2}, {3, 4}, {5, 6}}; //声明并初始化一个整型二维数组```3. Java中常用的集合类有哪些?答:Java中常用的集合类有ArrayList、LinkedList、HashSet、TreeSet、HashMap和TreeMap等。
thinkinginjava笔记

thinkinginjava笔记Java笔记(thinkinginjava)★类是由若干对象构成的一个集合◆这些对象具有相同属性(数据元素)和行为(功能)★基类和派生类具有相同的类型泛型(Generic)★不依赖于特定类型的代码终极基类的名字就是Object◆+意味着字符串连接,并且如果必要,它还要进行字符串转换★如果将对象作为参数传递时,实际上传递的是一个引用★!=和==也适用于所有对象◆但要注意:不是比较对象本身,而是比较对象的引用★如果想比较两个对象的实际内容是否相同,又该如何操作呢?◆此时,必须使用所有对象都适用的特殊方法equal()(Java类的老祖宗Object提供)Java语言与C/C++所不同的是,不可将一个非布尔值当成是一个布尔值在逻辑表达式中使用◆但Java的设计者还是觉得操作符重载过于复杂,从而不提供操作符重载★Java唯一用到逗号操作符的地方就是for循环的控制表达式★JavaSE5引入一种新的更加简洁的语法来访问数组和容器,即Foreach语法利用该语法,可以不必再创建int变量来对访问项构成的序列进行计数声明数组的语法:数组元素类型数组名[];数组元素类型[]数组名;//补充2:创建数组空间的语法:数组名=new数组元素类型[数组元素个数];★构造器是一种特殊类型的方法,因为它没有返回值方法重载的概念★方法名相同,而参数类型列表不同◆也就是依靠参数的个数、类型和顺序的不同加以区分(后者不推荐使用)★如果你写的类没有构造器,那么编译器会自动帮你创建一个默认构造器(无参构造器)thi关键字的含义★概念:指向对象本身的引用成员函数是怎么知道它究竟被哪个对象调用的?◆答案是:通过thi关键字(编译器自动完成)★为避免重复代码,往往使用thi关键字★如果用户没有编写析构函数,编译系统会自动生成一个缺省的析构函数,而它也不进行任何操作★垃圾回收器只知道释放那些经由new关键字分配的内存是否存在不经new分配的内存?答案:确实存在着不经new分配的内存(利用本地方法调用非Java代码,如C的malloc函数)★问题2:垃圾回收器是否知道如何释放这块特殊的内存?◆答案很显然:不知道◆那么这块特殊的内存如何释放呢?Java允许在类中定义一个finalize()方法,可以通过调用该方法来实现★问题3:垃圾回收器是否等同于析构函数?◆不等同(范围不等同)★Java的变量有两种:引用变量和基本类型变量,后者又分为下面两种情况★Java以编译时错误的形式来保证其初始化★Java将为类的每个基本数据成员提供自动初始化(保证都会有一个初始值)★无论是否数据成员,如果不将其初始化,该对象引用会被Java自动赋值为null初始化的第一基本原则★可以用构造器来进行初始化◆但执行顺序是:先自动初始化,再指定初始化,最后调用构造器进行初始化★变量定义的先后顺序决定其初始化顺序◆不管这些变量的定义位于什么地方,它们一定会在任何方法(包括构造器)被调用之前得到初始化★初始化的第二基本原则◆初始化的顺序是先静态对象,而后是非静态对象◆类在必要的时候才会被加载◆静态对象的初始化发生在类的加载时期◆非静态对象的初始化发生在创建对象时期数组的声明(P99)★如:int[]a;或者inta[];★仅仅声明了对数组的一个引用,而且也没有给数组对象本身分配任何空间数组元素的类型可以是对象引用,这种数组称为引用数组★注意对引用数组进行初始化,否则在程序中所使用的是空引用(null)可变参数列表★应用于参数个数或类型未知的场合利用封装和访问权限控制来解决该程序存在重构的可能和必要,但是类的消费者却希望你的代码保持不变矛盾,保证接口的声明和接口的功能保持不变访问权限控制的第一基本原则:尽可能将一切数据和方法设为private,而允许类的消费者访问和使用的方法设为public每个Java文件都有一个public类(主类)以及若干个非public类(辅助类)◆注意:包的定义必须是文件中除注释以外的第一条语句注意:Vector类和Lit类属于同一个包★Java访问权限修饰词包含四种:public、private、protected、缺省◆如果没有提供任何访问权限修饰词,则意味它是包访问权限protected:=子类+包访问权限★访问权限控制的第二基本原则:类消费者一般不能享有包访问权限◆防止类的消费者访问并修改包中的类★解释:toString()方法◆每一个非基本类型的对象都有一个toString方法可以为每个类都创建一个main方法★Java会自动在导出类的构造器中插入对基类构造器的调用★必须用关键字uper显示地调用基类的构造器重载的定义★类对自身已有的同名方法的重新定义重载的本质★利用不同的参数列表,包括形式参数的个数、类型、顺序的不同来区分重载覆盖的定义★子类对继承自父类方法的重新定义覆盖的本质★是指在子类中定义了这样的一个方法:该方法具有与父类完全相同的返回值类型、方法名和参数列表(但是重新编写了方法体)重载与覆盖的区别★关键:发生的地点不同◆重载发生在同一个类中◆覆盖发生在基类与派生类中如果Java的基类拥有某个已被多次重载的方法,那么在导出类中重新定义该方法并不会覆盖在基类的任何版本★向上转型是从一个较专用类型向较通用类型转换所以总是很安全◆导出类是基类的一个超集,它必须至少具备基类中所含有的所有方法常量可以进一步细分为:★编译期常量◆编译期间就能确定它的值★非编译期常量◆直到运行期间才能确定它的值一旦引用被初始化指向一个对象,就无法再把它指向另一个对象★然而,对象其自身却是可以修改的★按照惯例:一个既是tatic又是final的域,将采用大写字母表示,并且单词之间用下划线分隔final与taticfinal的区别在于:尽管都属于常量,但后者是属于类这个层次的,将在类被装载的时候被初始化,而不是每次创建对象时都初始化◆每个类的编译代码都存在于它自己独立的文件中,该文件只有在需要使用程序代码时才会被加载★面向对象的三大基本特征◆抽象与封装、继承、多态★通过封装和访问控制,可以对类中的数据成员和成员函数起到保护作用★多态是面向对象最核心的机制,多态使程序的可扩展性达到了极至多态的本质★多态方法调用允许一种类型表现出与其它相似类型之间的区别,只要它们都是从同一基类导出来的★继承与多态的重要区别◆继承侧重于:父类的成员将原封不动的遗传给子类◆多态侧重于:父类的成员将会在子类中被覆盖,即父类的成员在子类中具有各种各样的形态◆多态,也称为动态绑定,指的是在执行期间(而非编译期间)判断所引用对象的实际类型,根据其实际的类型调用其相应的方法使用多态的三个条件:继承、覆盖与向上转型一个基类绝非只有一个子类多态是将改变的事物与未改变的事物分离开来的重要技术绑定(Banding)的概念★将一个方法调用和一个方法主体关联起来的过程称为绑定绑定(Banding)的分类⑴静态绑定(前期绑定,编译时绑定)★在运行前进行绑定⑵动态绑定(后期绑定、运行时绑定)★在运行的时候根据对象的类型进行绑定★向上转型的归纳:基父类实例=new子类();◆向上转型时,实例可以调用父类中所有特有的方法(未在子类中覆盖的方法)◆实例可以调用子类中覆盖父类的方法(即多态)◆但是不可以调用子类中特有的方法(即父类中没有的方法)注意:只有普通的方法调用可以是动态绑定的,域与静态方法不存在动态绑定★任何域的解析都是在编译期间进行的★静态方法是类的方法(不存在与对象的绑定)在一般方法的内部,动态绑定的调用是在运行时才决定的★只要子类方法与超类方法具有相同的方法签名,或者子类方法的返回值是超类方法的子类型,就可以覆盖抽象类的概念★包含抽象方法的类称为抽象类★创建抽象类的目的在于:抽象类为它的所有导出类创建了一个通用接口◆不同的子类使用不同的方式实现此接口Ⅰ不能为抽象类创建其对象★否则,编译器就会报错Ⅱ如果继承一个抽象类并试图创建该类的对象,那么就必须为基类中的所有抽象方法提供方法定义interface的访问权限控制有两种:◆Public◆缺省(包访问权限控制)interface中方法的访问权限控制只有一种◆public(缺省),否则编译器报错★Interface的主要作用在于:利用接口来实现类似多重继承的机制◆Java不支持多重继承抽象类可以提供某些方法的部分实现,然而接口不可以接口中的域隐式是tatic和final的★这是抽象类唯一的优点,但这个优点却非常有用★Interface的主要作用在于:利用接口来实现类似多重继承的机制◆Java不支持多重继承接口的最大优点是实现了多重继承的机制★接口的这个优点却是抽象类的一个致命缺陷◆任何一个实现了一个接口所规定的方法的类,都可以具有这个接口的类型◆而一个类可以实现任意多个接口,从而这个类就具有了多种类型(不像抽象类,后者如果想具有某种类型则必须加入某一棵继承树中)★归纳:缺省适配模式的概念◆在类的层次结构中,接口在最上面,然后紧跟着抽象类,这样接口和抽象类的最大优点都能发挥到极至匿名内部类不能有构造函数★构造函数与类名一致,但是现在这个类连名字都没有匿名内部类不能定义任何静态的成员、方法★更进一步,匿名内部类本身也不能为tatic的使用new关键字创建匿名类对象,并且返回一个指向该匿名内部类对象的引用;◆如果你有一个匿名内部类,它要使用一个在它的外部定义的对象,编译器会要求它的参数引用是final型的嵌套类(netedcla)的概念★嵌套类也称为静态内部类★如果不需要内部类对象与其外部类对象为tatic的◆这种内部类通常称为嵌套类嵌套类的性质⑴要创建嵌套类的对象,并不需要其外部类的对象★静态内部类的对象可以直接生成,例如:◆Outer.Innerin=newOuter.Inner();从嵌套类访问外部类的原则★嵌套类可以访问外部类的静态成员★但不能够访问外部类的非静态成员从外部类访问嵌套类的原则★访问嵌套类静态成员的方法★访问嵌套类非静态成员的方法闭包(cloure)的概念★指内部函数通过某种方式使其可见范围超出了其定义范围,这就产生一个在其定义范围内的闭包内部类可操作所有外部类的成员内部类是一个闭包如果想在外部类的某个非静态方法中,创建某个内部类的对象◆直接创建即可◆当某个外部类的对象创建了一个内部类对象时,此内部类对象必定会秘密捕获一个,指向那个外部类对象的引用◆内部类正是通过该引用来访问外部类成员如果你需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟.thi创建内部类的原则★必须明确的是:内部类对象是不能直接创建的必须先创建一个外部类对象,再由这个外部类对象来创建内部类对象一个外部类对象可创建多个内部类对象★创建内部类对象的.new语法◆OuterClaObj.newInnerCla()在一个方法的里面创建出一个完整的内部类★这种内部类也称为局部内部类Iterable表示可迭代◆要使用下标才能访问数组中的每个元素◆集合也一样,但是集合不支持下标运算,所以就必须提供一个可访问集合中任意元素的工具,而这个工具就是迭代器◆把Java对象转换为字节序列的过程称为序列化◆把字节序列恢复为Java对象的过程称为反序列化Object[]toArray()非常重要的方法:数据转换的桥梁★intize()//返回大小★booleaniEmpty()//判断是否非空★voidclear()//清空★booleanequal(Objecto)//比较◆LinkedLit的底层实现方式为双向循环链表:链表中的每个结点除了数据本身外,还有两个引用,分别指向前一个元素和后一个元素◆可以利用LinkedLit实现栈、队列和双向队列★LinkedLit有两个构造函数◆TreeSet是一个有序集合,TreeSet中元素将按照升序排列,缺省是按照自然顺序进行排列★TreeSet是依靠TreeMap来实现的★TreeSet是依靠TreeMap来实现的★TreeSet类有4个构造函数★HahSet是依靠HahMap来实现的◆HahSet类是实现Set接口的hahtable(哈希表)◆HahSet实现了et接口,所以不能有重复元素◆那么这个散列表是如何判定元素是否重复的?答案:通过hahCode ()和equal()判别★HahSet有4个构造函数◆Map是从键到值的映射,键不允许重复,每个键最多能映射一个值★以Map接口为根的集合类主要用于存储关键字(key)和值(value)的元素对◆Map接口的两个主要实现是HahMap类和TreeMap类Map.Entry<K,V>接口的声明★publictaticinterfaceMap.Entry<K,V>★new关键字的重要作用:⑴申请存储空间⑵创建对象并使用构造函数初始化⑶返回指向该对象的一个引用泛型机制将运行时异常转变为编译时错误Array.aLit()方法的返回值★返回一个定长的Lit,所以不能再将它转换为ArrayLit(可变长数组)★Collection和Collection的区别1、Collection是java.util下的接口,是各种集合结构的父接口;该接口的意义是为各种具体的集合提供了最大程度的统一操作方式2、Collection是java.util下的类,里面包含各种有关集合操作的静态方法;该类不能实例化,就像一个工具类,服务于Java的Collection框架★Collection.addAll(collection,11,12,13,14,15);◆Collection.addAll()方法接受一个Collection对象,以及一个数组或者是一个用逗号分隔的列表,将元素添加到Collection中★collection.addAll(Array.aLit(moreInt));◆Collection.addAll()只能接受另一个Collection对象作为参数,因此不如Array.aLit()或者Collection.addAll()灵活,后两个方法都可以使用可变参数列表◆但是它的速度更加快,因此是首选方式1、ArrayLit的优缺点★优点:随机访问◆缺点:插入、删除和移动元素较慢2、LinkedLit的优缺点★同ArrayLit相反◆注意:LinkedLit的方法集(39个方法)比ArrayLit(20个方法)的更大迭代器(Iterator)的概念★迭代器是一个对象◆主要作用是:用来抓取容器中的元素,并将抓取到的元素提交给迭代器用户迭代器的声明★publicinterfaceIterator<E>★栈是一种后进先出(LIFO)的容器★因此可以直接将LinkedLit当成栈使用Set的概念★Set是一种不保存重复元素的Collection◆实际上,Set具有与Collection完全一样的接口,只是行为不同(而这正是多态的典型应用)⑴TreeSet★将元素存储于红黑树的数据结构中⑵HahSet★使用散列函数⑶LinkedHahSet★使用链表来维护元素的插入顺序★Queue是一种典型的先进先出(FIFO)的容器Queue接口的声明★publicinterfaceQueue<E>e某tendCollection<E>★根据错误被发现的时间,我们可以将错误分为两大类型:◆编译阶段的错误◆运行阶段的错误异常(E某ception)的概念★异常是一个描述在代码段中所发生的出错情况的对象Throwable类◆只有这个类(或其子类)的对象才能够被JVM或者Java的throw 子句所抛出StackTrace:堆栈跟踪信息★该方法每次执行的时候,会清空原来的堆栈跟踪信息,然后在当前调用位置处重新填写跟踪信息printStackTrace★还有两个重载的printStackTrace方法★功能:将当前异常对象的堆栈跟踪信息,输出到标准错误流(Sytem.err)Error类的概念:★不可恢复的系统级的错误。
JAVA教程答案(第四版)
= = = = = = = = = = = = =
1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13;
public Card(int rank, int suit) { assert isValidRank(rank); assert isValidSuit(suit); this.rank = rank; this.suit = suit; } public int getSuit() { return suit; } public int getRank() { return rank; } public static boolean isValidRank(int rank) { return ACE <= rank && rank <= KING; } public static boolean isValidSuit(int suit) { return DIAMONDS <= suit && suit <= SPADES; } public static String rankToString(int rank) { switch (rank) { case ACE: return "Ace"; case DEUCE: return "Deuce"; case THREE:
if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string");
Access数据库应用基础教程(第四版)习题答案
附录各章习题参考答案第1章习题参考答案1.10.1 思考题1. 答:数据库是指长期存储在计算机内的、有组织的、可共享的、统一管理的相关数据的集合。
数据库系统是计算机化的记录保持系统,它的目的是存储和产生所需要的有用信息。
通常,一个数据库系统要包括以下4个主要部分:数据、用户、硬件和软件。
2. 数据库管理系统是位于用户和数据库之间的一个数据管理软件,它的主要任务是对数据库的建立、运用和维护进行统一管理、统一控制,即用户不能直接接触数据库,而只能通过DBMS来操纵数据库。
通常情况下,DBMS提供了以下几个方面的功能。
●数据库定义功能:DBMS提供相应数据定义语言定义数据库结构,刻画数据库的框架,并被保存在数据字典中。
数据字典是DBMS存取和管理数据的基本依据。
●数据存取功能:DBMS提供数据操纵语言实现对数据库数据的检索、插入、修改和删除等基本存取操作。
●数据库运行管理功能:DBMS提供数据控制功能,即数据的安全性、完整性和并发控制等,对数据库运行进行有效的控制和管理,以确保数据库数据正确有效和数据库系统的有效运行。
●数据库的建立和维护功能:包括数据库初始数据的装入,数据库的转储、恢复、重组织、系统性能监视、分析等功能。
这些功能大都由DBMS的实用程序来完成。
●数据通信功能:DBMS提供处理数据的传输功能,实现用户程序与DBMS之间的通信,这通常与操作系统协调完成。
3. 数据库中的数据是结构化的,这是按某种数据模型来组织的。
当前流行的基本数据模型有3类:关系模型、层次模型和网状模型。
它们之间的根本区别在于数据之间联系的表示方式不同。
关系模型是用二维表来表示数据之间的联系;层次模型是用树结构来表示数据之间的联系;网状模型是用图结构来表示数据之间的联系。
层次模型和网状模型是早期的数据模型。
通常把它们通称为格式化数据模型,因为它们是属于以“图论”为基础的表示方法。
4. 关系模型(Relational Model)是用二维表格结构来表示实体及实体之间联系的数据模附录各章习题参考答案• 7 •型。
JAVA编程思想第四版第二章
1.public class HelloWorld2.{3.public static void main(String[] args)4.{5.System.out.println("Hello,World");6.}7.}(2) 写一个程序,打印出从命令行获取的三个自变量。
[java]view plaincopyprint?1.public class GetArgs2.{3.public static void main(String[] args)4.{5.System.out.println(args[0]);6.System.out.println(args[1]);7.System.out.println(args[2]);8.}9.}10.//java GetArgs a 3 12(3)[java]view plaincopyprint?1.class Tree{2.3.int height;4.5.Tree(){6.System.out.println("Planting a seedling");7.height=0;8.}9.10.T ree(int initialHeight){11.h eight =initialHeight;12.S ystem.out.println("Creating new tree that is"+height+" feet tall");13.}14.15.v oid info()16.{17.S ystem.out.println("Tree is "+height+" feettall");18.}19.20.v oid info(String s){21.S ystem.out.println(s+":Tree is "+height+"feettall");22.}23.}24.25.p ublic class OverLoading{26.p ublic static void main(String[] args){27.n ew Tree();28.f or (int i=0;i<5;i++){29.T ree t=new Tree(i);();("overloading method");32.}33.34.}35.}输出结果:Microsoft Windows [版本6.1.7600]版权所有(c) 2009 Microsoft Corporation。
java编程思想第四版 习题答案
java编程思想第四版习题答案
《Java编程思想第四版习题答案》
在学习编程语言Java的过程中,深入理解和掌握其编程思想是至关重要的。
《Java编程思想第四版》作为一本经典的Java编程教材,不仅系统地介绍了Java语言的基本知识和技术,还提供了丰富的习题和练习,帮助读者更好地理
解和运用所学知识。
本书的习题答案部分,包含了大量的编程实例和解题思路,涵盖了Java编程的
各个方面,从基础的数据类型和控制流程,到面向对象编程、异常处理、多线
程等高级主题,无一不展现了Java编程思想的精髓和实用性。
通过阅读和学习《Java编程思想第四版》的习题答案,读者不仅可以加深对
Java语言的理解,还能够提升自己的编程能力和解决问题的能力。
同时,通过
实际的编程练习,读者还可以更好地掌握Java编程的规范和技巧,提高代码的
质量和效率。
总之,《Java编程思想第四版习题答案》是一本不可多得的Java编程学习资料,它不仅帮助读者打好扎实的编程基础,还能够引领他们进入Java编程的精妙世界,成为一名优秀的Java程序员。
希望广大Java爱好者能够认真阅读和学习
本书,不断提升自己的编程水平,为未来的发展打下坚实的基础。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Thinking in Java 4th Edition习题答案1.Access部分(NO.1) // access/AccessTest.java// TIJ4 Chapter Access, Exercise 5, page 227/* Create a class with public, private, protected and package-access fields and* method members. Create an object of this class and see what kind of compiler* messages you get when you try to access all the class members. Be aware that* classes in the same directory are part of the "default" package.*//* in same directory:* package access;** public class FourWays {* int a = 0;* public int b = 1;* protected int c = 2;* private int d = 3;* FourWays() { System.out.println("FourWays() constructor"); }* void showa() { System.out.println(a); }* public void showb() { System.out.println(b); }* protected void showc() { System.out.println(c); }* private void showd() { System.out.println(d); }* }*/package access; // run command java access.AccessTestpublic class AccessTest {public static void main(String[] args) {FourWays fw = new FourWays();fw.showa();fw.showb();fw.showc();fw.a = 10;fw.b = 20;fw.c = 30;fw.showa();fw.showb();fw.showc();//! fw.showd(); // private access, compiler can't touch}}(NO.2)// access/Collision.java// TIJ4 Chapter Access, Exercise 2, page 217/* Take the code fragments in this section and turn them into a program and* verify that collisions do occur.*/import net.mindview.simple.*;import java.util.*;public class Collision {public static void main(String[] args) {// Vector v = new Vector(); // ambiquous collisionnet.mindview.simple.Vector v1 = new net.mindview.simple.Vector();java.util.Vector v2 = new java.util.Vector();}}(NO.3)// access/ConnectionManager.java// TIJ4 Chapter Access, Exercise 8, page 233/* Following the form of the example Lunch.java, create a class called* ConnectionManager that manages a fixed array of Connection objects. The client * programmer must not be able to explicitly create Connection objects, but can* only get them via a static method in ConnectionManager. When ConnectionManager* runs out of objects, it returns a null reference. Test the classes in main(). */ package access;class Connection {private static int count = 0;private int i = 0;private Connection() { System.out.println("Connection()");}// Allow creation via static method:static Connection makeConnection() {count++;return new Connection();}public static int howMany() { return count; }public String toString() {return ("Connection " + count);}public class ConnectionManager {static int howManyLeft = 3;static Connection[] ca = new Connection[3];{for(Connection x : ca)x = Connection.makeConnection();}public static Connection getConnection() {if(howManyLeft > 0)return ca[--howManyLeft];else {System.out.println("No more connections");return null;}}public static void main(String[] args) {ConnectionManager cm = new ConnectionManager();System.out.println(cm.howManyLeft);cm.getConnection();System.out.println(howManyLeft);cm.getConnection();System.out.println(howManyLeft);cm.getConnection();System.out.println(cm.getConnection());System.out.println(howManyLeft);}}(NO.4)// access/cookie2/CookieMonster.java// TIJ4 Chapter Access, Exercise 4, page 227// Show that protected methods have package access but are not public. /* In directory Cookie2:* //access/cookie2/Cookie.java* //Creates a library* package access.cookie2;** public class Cookie {* public Cookie() {* System.out.println("Cookie contstructor");* }* protected void bite() { System.out.println("bite"); }*/package access.cookie2;public class CookieMonster {public static void main(String[] args) {Cookie x = new Cookie();x.bite(); // package access to protected method}}(NO.5)// access/debug/Debug.java// TIJ4 Chapter Access, Exercise 3, page 220/* Create two packages: debug and debugoff, containing an identical class with a * debug() method. The first version displays its String argument to the console, * the second does nothing. Use a static import line to import the class into a test * program, and demonstrate the conditional compilation effect.*//* In directory access/debugoff:* // access/debugoff/Debug.java* package access.debugoff;** public class Debug {* public static void debug(String s) { }* }*/package access.debug;public class Debug {public static void debug(String s) {System.out.println(s);}}(NO.6)// TIJ4 chapter Access, Exercise 9, page 233/* Create in access/local directory in your CLASSPATH:* // access/local/PackagedClass.java* package access.local;* class PackagedClass {* public PackagedClass() {* System.out.println("Creating a packaged class");* }* }* // Then, in another directrory create the file below and explain why compiler* generates error. Would making Foreign class part of access.local change anything? */// access/foreign/Foreign.javapackage access.foreign;import access.local.*;public class Foreign {public static void main(String[] args) {PackagedClass pc = new PackagedClass();}}/* Compiler error because: PackagedClass in not public, so no access outside of* package. Moving Foreign to local would allow package access to PackagedClass. */(NO.7)// MakeWidget.java// TIJ4 Chapter Access, Exercise 7, page 230/* Create the library according to the code fragments describing access and Widget. * Create a Widget in a class that is not part of the access package.*//* in access package:* // access/Widget.java* package access;** public class Widget {* public Widget() { System.out.println("Widget()"); }* }*/import access.*;public class MakeWidget {public static void main(String[] args) {Widget w = new Widget();}}(NO.8)// access/ProtectedData.java// TIJ4 Chapter Access, Exercise 6, page 228/* Create a class with protected data. Create a second class in the same file with* a method that manipulates the protected data in the first class.*/class SomeData {protected int a = 13;}class DataChanger {static void change(SomeData sd, int i) { sd.a = i; }}public class ProtectedData {public static void main(String[] args) {SomeData x = new SomeData();System.out.println(x.a);DataChanger.change(x, 99);System.out.println(x.a);}}(NO.9)// access/UnpackagedMyClass.java// TIJ4 Chapter Access, Exercise 1, page 217// Create a class in a package. Create an instance of your class outside of that package./* In another directory:* // access/mypackage/MyPackagedClass.java** package access.mypackage;** public class MyPackagedClass {* public MyPackagedClass() {System.out.println("MyPackagedClass()");}* }*/public class UnpackagedMyClass {public static void main(String[] args) {access.mypackage.MyPackagedClass m = new access.mypackage.MyPackagedClass();}}// arrays/ArrayOfGenerics10.java// TIJ4 Chapter Arrays, Exercise 10, page 762// Modify ArrayOfGeneric.java to use containers instead of arrays. // Show that you can eliminate the compile-time warnings. import java.util.*;public class ArrayOfGenerics10 {@SuppressWarnings("unchecked")public static void main(String[] args) {List<List<String>> lls = new ArrayList<List<String>>();List<List> l = new ArrayList<List>();// lls = (List<List<String>>)l; // error: inconvertible typeslls.add(new ArrayList<String>());List<Object> lo = new ArrayList<Object>();// lo = lls; // error: incompatible types// Compile-time warning eliminated:List<List<BerylliumSphere>> llb =new ArrayList<List<BerylliumSphere>>();for(int i = 0; i < 10; i++) {llb.add(new ArrayList<BerylliumSphere>());for(int j = 0; j < 2; j++)llb.get(i).add(new BerylliumSphere());}System.out.println(llb);}}// arrays/ContainerComparison15.java// TIJ4 Chapter Arrays, Exercise 15, page 775// Modify ContainerComparison.java by creating a Generator for // BerylliumSphere, and change main() to use that Generator// with Generated.array().import net.mindview.util.*;import java.util.*;import static net.mindview.util.Print.*;class BerylliumSphereGenerator implements Generator<BerylliumSphere> { public BerylliumSphere next() {return new BerylliumSphere();}}public class ContainerComparison15 {public static void main(String[] args) {BerylliumSphere[] spheres = new BerylliumSphere[5];BerylliumSphereGenerator bsg = new BerylliumSphereGenerator();Generated.array(spheres, bsg);print(Arrays.toString(spheres));print(spheres[4]);List<BerylliumSphere> sphereList =new ArrayList<BerylliumSphere>();for(int i = 0; i < 5; i++)sphereList.add(bsg.next());print(sphereList);print(sphereList.get(4));}}// arrays/Ex1.java// TIJ4 Chapter Arrays, Exercise 1, page 752/* Create a method that takes an array of BerylliumSphere 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.*;class A { public String toString() { return "A Object"; } }public class Ex1 {// Method that takes BerylliumSphere[] as argument// and prints the argument as array elements and as List or String:public static void test(BerylliumSphere[] 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., BerylliumSpheres:");// Array is created and initialized (aggregate initialization)// but all elements are null, not BerylliumSpheres:test(new BerylliumSphere[3]);// Dynamic aggregate initialization works;// elements are now BerylliumSpheres:test(new BerylliumSphere[]{new BerylliumSphere(), new BerylliumSphere() });// Aggregate initialization this way works:BerylliumSphere[] a = { new BerylliumSphere(),new BerylliumSphere(), new BerylliumSphere() };test(a);// Elements initialized to null:BerylliumSphere[] bsa = new BerylliumSphere[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);}}// arrays/Ex11.java// TIJ4 Chapter Arrays, Exercise 11, page 774// Show that autoboxing doesn't work with arrays.import static org.greggordon.tools.Print.*;public class Ex11 {public static void main(String[] args) {int[] ia = new int[2];ia[0] = new Integer(1); // will be autoboxed to intia[0] = new Integer(2); // autoboxing does work here// an array of primitive int:println(ia.getClass().getName());Integer[] Ia = new Integer[2];Ia[0] = (int)1; // will be autoboxed to IntegerIa[1] = (int)2; // autoboxing works here// an array of Integer:println(Ia.getClass().getName());println(Ia[0] instanceof Integer);for(int i = 0; i < Ia.length; i++)System.out.println(Ia[i].getClass().getName());// Integer[] cannot be assigned to int[]:// ia = Ia; // error: incompatible typesIa[0] = (int)ia[0]; // more autoboxingprintln(Ia[0].getClass().getName());}}。