#chapter8 对象的容纳
如果一个程序只含有数量固定的对象,而且已知它们的存在时间,那么这个程序可以说是相当简单的
要求能在任何时候、任何地点创建任意数量的对象
1.数组
有两方面的问题将数组与其他集合类型区分开来:效率和类型
为保存和访问一系列对象(实际是对象的句柄)数组,最有效的方法莫过于数组
集合只能保存对象句柄,数组可以保存对象句柄和基本类型
在Java 中,无论使用的是数组还是集合,都会进行范围检查——若超过边界,就会获得一个RuntimeException(运行期违例)错误
Vector(矢量)、Stack(堆栈)以及 Hashtable(散列表)它们将对象类型当作 Object 类型处理(上溯造型)仅需构建一个集合,然后任何Java 对象都可以进入那个集合
考虑到执行效率和类型检查,应尽可能地采用数组
对象本身是在内存“堆”里创建的。堆对象既可“隐式”创建(即默认产生),亦可“显式”创建(即明确指定,用一个new表达式)。
堆对象的一部分(实际是我们能访问的唯一字段或方法)是只读的length(长度)成员,它告诉我们那个数组对象里最多能容纳多少元素
对象数组容纳的是句柄,而基本数据类型数组容纳的是具体的数值
在任何地方创建和初始化一个数组对象hide(new Weeble[] {new Weeble(), new Weeble() });
若能创建和访问一个基本数据类型数组,那么比起访问一个封装数据的集合,前者的效率会高出许多。当然,假如准备一种基本数据类型,同时又想要集合的灵活性(在需要的时候可自动扩展,腾出更多的空间)就不宜使用数组,必须使用由封装的数据构成的一个集合
package com.yiz.chapter8;
/**
* @ClassName: ArraysLength
* @Description: 数组存储对象
* @return
* @parameter
* @author : yizhou
* @date :2018年1月10日 下午10:33:22
* @version 1.0
*/
class Tree{
}
public class ArraysLength {
public static void main(String[] args) {
Tree[] trees;
Tree[] trees2=new Tree[4];
Tree[] trees3=new Tree[5];
//wrong must be initalization
//System.out.println(trees.length);
System.out.println(trees2.length);
System.out.println(trees3.length);
System.out.println(trees3[0]);
//未初始化对象数组中成员为null
for (Tree tree : trees3) {
System.out.println(tree);
}
System.out.println();
//初始化trees3
for (int i = 0; i < trees3.length; i++) {
trees3[i]=new Tree();
}
System.out.println();
for (Tree tree : trees3) {
System.out.println(tree);
}
//将trees3的句柄赋给trees
trees=trees3;
System.out.println();
for (Tree tree : trees) {
System.out.println(tree);
}
}
}
4
5
null
null
null
null
null
null
com.yiz.chapter8.Tree@659e0bfd
com.yiz.chapter8.Tree@2a139a55
com.yiz.chapter8.Tree@15db9742
com.yiz.chapter8.Tree@6d06d69c
com.yiz.chapter8.Tree@7852e922
com.yiz.chapter8.Tree@659e0bfd
com.yiz.chapter8.Tree@2a139a55
com.yiz.chapter8.Tree@15db9742
com.yiz.chapter8.Tree@6d06d69c
com.yiz.chapter8.Tree@7852e922
2.数组的返回
返回的实际仍是指向数组的指针
package com.yiz.chapter8;
class Strings{
static String[] strings= {
"this is a ",
"this is b ",
"this is c ",
};
public static String[] getStrings(){
return strings;
}
}
/**
* @ClassName: ArraysReturn
* @Description: return a String Arrays handle
* @return
* @parameter
* @author : yizhou
* @date :2018年1月10日 下午11:11:05
* @version 1.0
*/
public class ArraysReturn {
public static void main(String[] args) {
String[] s=Strings.getStrings();
//compare two StringArrays' adress
System.out.println(Strings.strings);
System.out.println(s);
//change the value of s and the value of Strings.strings is changed too
for (int i = 0; i < s.length; i++) {
s[i]="changed";
}
for (int i = 0; i <Strings.strings.length; i++) {
System.out.println(Strings.strings[i]);;
}
}
}
[Ljava.lang.String;@659e0bfd
[Ljava.lang.String;@659e0bfd
changed
changed
changed