CSDN翁恺老师
一、简单理解
当数组的元素的类型是类的时候,数组的每一个元素其实只是对象的管理者而不是对象本身。因此,仅仅创建数组并没有创建其中的每一个对象!
二、例子:String数组
2.1 文字解释:
String s = new String(); s只是管理者,并不是存储数据的地方。
String[] s = new String[10]; 只是创建了10个String的管理者。并没有初始化所要指向的对象。
如下:
2.2 代码示例:
//实现记事本功能
import java.util.ArrayList;
class Value{
private int i;
private void set(int i){
this.i = i;
}
public int get(){
return i;
}
}
public class NoteBook{
//泛型容器类
private ArrayList<String> notes = new ArrayList<String>();
//一系列接口
public void add(String s){
notes.add(s);
}
public void add(String s, int location){
notes.add(location, s);
}
public int getSize(){
return notes.size();
}
public String getNote(int index){
return notes.get(index);
}
public void removeNote(int index){
notes.remove(index);
}
public String[] list(){
String[] a = new String[notes.size()];
for(int i=0; i<notes.size(); i++){
a[i] = notes.get(i);
}
//notes.toArray(a);//相当于for循环的遍历
return a;
}
public static void main(String[] args){
//String数组
String[] a = new String[10];//创建了10个管理者
for(int i=0; i<a.length; i++) {//有了具体可指向的对象
a[i] = " "+ i;
}
//对象数组
Value[] a = new Value[10];
for(int i=0; i<a.length; i++) {
a[i] = new Value();
a[i].set(i);
}
for(Value v : a) {//v是管理者和a数组的元素共同管理同一个对象
System.out.println(v.get());
v.set(0);//改变了Value中的值
}
for(Value v : a) {
System.out.println(v.get());
}
//一般数组
int[] ia = new int[10];
for(int i=0; i<ia.length; i++) {
ia[i] = i;
}
for(int k : ia) {
k++;//不会起到任何作用,即不会改动原数组//因为k只是每次所取元素的复制品,而不是原数组的元素
// System.out.println(k);
}
for(int k : ia) {
System.out.println(k);
}
}
}
后续会继续补充