Chapter 6 Single-dimensional Arrays
3 声明数组时不分配内存 。
创建数组时分配内存。
x is 60
The size of numbers is 30
4.
1. 数组中每个元素都有相同的类型。
Answer: True
2. 一旦数组被声明,大小不能改变。
Answer: False
3. 一旦数组被创建,大小不能改变。
Answer: True
4. 数组中的元素必须是基本数据类型。
Answer: False
5. Which of the following statements are valid array declarations?
int i = new int(30);
Answer: Invalid
double d[] = new double[30];
Answer: Valid
char[] r = new char(1..30);
Answer: Invalid
int i[] = (3, 4, 3, 2);
Answer: Invalid int i[] = {3, 4 ,3, 2};
float f[] = {2.3, 4.5, 5.6};
Answer: Valid
char[] c = new char();
Answer: Invalid char[] c = new char[];
6. 数组下表类型是 int ,最小下标是0.
a[2]
7.
(a)
double[] list = new double[10];
(b)
list[list.length – 1] = 5.5;
(c)
System.out.println(list[0] + list[1]);
(d)
double sum = 0;
for (int i = 0; i < list.length; i++)
sum += list[i];
(e)
double min = list[0];
for (int i = 1; i < list.length; i++)
if (min > list[i]) min = list[i];
(f)
System.out.println(list[(int)(Math.random() * list.length));
(g)
double[] = {3.5, 5.5, 4.52, 5.6};
8. 发生异常。
9. Line 3: the array declaration is wrong. It should be double[]. The array needs to be created before its been used. e.g. new double[10]
Line 5: The semicolon (;) at the end of the for loop heading should be removed.
Line 5: r.length() should be r.length.
Line 6: random should be random()
Line 6: r(i) should be r[i].
10. System.arraycopy(source, 0, t, 0, source.length);
11. The second assignment statement myList = new int[20] creates a new array and assigns its reference to myList.
12. False. When an array is passed to a method, the reference value of the array is passed. No new array is created. Both argument and parameter point to the same array.
13.
numbers is 0 and numbers[0] is 3
14.
15. Only one variable-length parameter may be specified in a method and this parameter must be the last parameter. The method return type cannot be a variable-length parameter.
16. The last one
printMax(new int[]{1, 2, 3});
is incorrect, because the array must of the double[] type.
17. Omitted
18. Omitted
19. Omitted
20 Simply change (currentMax < list[j]) on Line 10 to (currentMax > list[j])
21 Simply change list[k] > currentElement on Line 9 to list[k] < currentElement
22. 除了boolean类型,其他任何类型都可以用. The sort method is void, so it does not return a new array.
23. java.util.Arrays.binarySearch(array, key), 必须用升序。
24. Line 1: list is {2, 4, 7, 10}
Line 2: list is {7, 7, 7, 7}
Line 3: list is {7, 8, 8, 7}
Line 4: list is {7, 8, 8, 7}