Arrays of Objects
对象数组 \color{#FF0000}{对象数组} 对象数组
●所谓对象数组,就是包含了一组相关的对象,但是在对象数组的使用中读者一定要清楚一点,数组一定要先开辟空间,但是因为其是引用数据类型,所以数组里面的每一个对象都是null值,则在使用的时候数组中的每一个对象必须分别进行实例化操作。
●对象数组的声明:
♦类 对象数组名称[] new 类[数组长度];
示例:
class Person{
private String name; //姓名属性
public Person(String name){ //通过构造方法设置内容
this.name = name; //为姓名赋值
}
public String getName(){ //取得姓名
return this.name;
}
}
public class ObjectArrayDemo01{
public static void main(String args[]){
Person per[] = new Person[3]; //声明一个对象数组,里面有三个对象
System.out.println("------数组声明-------");
for(int x = 0;x < per.length;x++){
System.out.print(per+"、")//循环输出
}
per[0] = new Person("张三");//实例化第一个元素
per[1] = new Person("李四");//实例化第二个元素
per[2] = new Person("王五");//实例化第三个元素
System.out.println("------对象实例化-------");
for(int x = 0;x < per.length;x++){
System.out.print(per[x].getName() + "、");
}
}
}
■So far,we have dealt with arrays of primitive data types(int double) values.
●Arrays to store objects can also be created.
Using the Car class,we can declare arrays to hold object references,as follows:
Car[] cars = new Car[MAX_CARS];//MAX_CARS is 10
●Then we can add Car references to the cars array as follows:
cars[0] = new Car("OOP101","Ford Falcon","Perth",35000);
cars[1] = new Car("OOP102","Nissan Cedric","Perth",2000);
cars[2] = new Car("GUI123","Ford Falcon","Perth",29000);
●The array can then be iterated in a loop as follows:
for(int i = 0;i < 3;i++)
System.out.println(car[i].getRego());
;
■With arrays of objects,each array element holds a reference to the object,not the object itself.
●Items can be added to and deleted from an array as the program is run.
●The logical size of the array,is the number of items currently stored.
●The maximum capacity of the array as given by its length property.
●Here,the capacity is 10,and the size is 3.
●For elements 3-9 the reference is by default set to null.
■In the preceding declarations,only three cars are stored in the array.
●if the preceding for loop were inadvertently coded as:
for(int i =0;i < cars.length;i++)
System.out.println(Cars[i].getRego());
●The output world print the registration number of the three cars and then terminate with a run-time exception:
OOP101
OOP102
GUI123
Exception in thread “main”
java.lang.NullPointerException
at
CarArrayDemo.main(CarArrayDemo.java:15)
■At this point cars[3] has no logical meaning - there is nothing there except null,and no object exists at that position.
●To guard against this,the for loop can be modified as:
for(int i = 0;i < cars.length && cars[i] != null;i++)//stop the loop when a null value is accessed.
System.out.println(cars[i].getRego());
collections(1)
■when grouping objects together,we end up with a collection.
●Most applications involve a collection of one or more objects.
●In the previous chapter,when processing the payroll,we had no way of storing individual Employee objects.
●With a collection of objects,common operations include:
-Creating the collection.
-Adding and removing items to/from the collection.
-travering the collection.
collections(2)
■There are a number of strategies for managing a collection,that include:
-Using a raw array,as with Car[] cars array.
-Using a class that acts as a container and providdes the code to manage the collection.
●By using a collection class,it is responsible for maintaining the collection.
●We could write our own collection class,or use one that is already provided in the Java API,such as ArrayList class.
●The ArrayList class has a number of methods,including:
- add():Adds an object at the end of the items in the list.
- indexOf():Searches for an object at the end of the - items and return its index.
- get():Gets an object at a specified index.
- size():Returns the number of elements stored in the array.
collections(3)
■In this section we will develop the CarList class to store a list of Car refer.
●It emulates a small subset of the methods in the ArrayList class.
●The CarList class helps in understanding how the ArrayList class works.
●In the CarList class,the array is a privatefield that is set in the constructor:
public class CarList{
private int count;//Number of cars in the yard
private Car[] cars;//The car database
public CarList(int maxLength){
cars = new Car[maxLength];
}
}
...
Adding to the List(1)
When adding to our list of cars,we need to ensure that:
●a non-existent car is not added to the list(a null car) and
●the size of the array is not exceeded(the container is not overfilled).
public boolean add(Car car){
if(car == null){
return false;//Can't add a null car
}
if(cars.length<count)
return false;//Array is full
cars[count++]=car;//add car to end of array
}
Searching the List(1)
■Arrays can be searched to determine whether they contain a certain item.
●The simplest way to search an array is sequentially:
-by examining each element of an array,starting at the first element,
-continuing one after another until either the search item is located,
-or the end of array is reached,-the search item is not found.
●if the element is found:
-the index of the element is returned,(hence the name,indexOf())
-otherwise -1 as an invalid array index is returned.
Searching the List(2)
■The indexOf() method uses sequential search for an item in an array:
public int indexOf(String regoToFind){
for(int index = 0;index<cars.length;index++){
if(cars[index].getRego().equals(regoToFind))
return index; //Rego found at index;
}
return -1;//Rego not found
}
Searching the List(3)
■the indexOf() method can be invoked as:
index = carList.indexOf(findRego);//Find rego in list
if(0 <= index){
car = carList.get(index);//Retrieve car from list
printCarDetails(car);//Print its details
}
else
System.out.println("Vehicle:"+findRego+"not found.");
Traversing Lists(1)
■Since our array is locked up inside the CarList container,we need to use the get() method to retrieve each object:
for(int i =0;i<fleetList.size();i++){
car = fleetList.get(i);
System.out.printf(" %-10s %-10s\n",car.getRego(),car.getLocation());
}
实例:
Student.java
class Student{
private String id;
private String name;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@
public String toString() {
return "Student{id = " + id + ", name = " + name + "}";
}
}
学生集合类StudentList.java
//自行实现的学生集合类,封装集合的创建、添加、删除、查找、获取大小、遍历等操作
public class StudentList {
//成员变量
Student list[];
int count;//集合中目前元素的个数
//成员方法
//创建:通过构造方法来实现
public StudentList(int max){
list = new Student[max];//数组初始化
count = 0;//集合中的元素个数
}
//讲一个对象添加到集合中,返回是否成功(失败:参数student为null或者数组满了)
public boolean add(Student student){
if(student == null){
return false; //参数为null,不能添加
}
//数组已满,不能添加
if(list.length <= count){
return false;//数组已满,不能添加
}
list[count]=student;
count++;
return true;
}
//删除操作,:删除指定位置的元素(index不在范围内,会失败)
public boolean remove(int index){
if(index>=count || index<0)
return false;
list[index] = null;
return true;
}
//接对象的某个字段(一般是关键字段)来查找,返回找到的对象在数组中首次出现的位置。如果没找到,则返回-1
public int indexOf(String id){
for(int i=0;i< list.length && list[i] != null;i++)//遍历条件
{
if(list[i].getId().equals(id))
return i;
}
return -1;//未找到
}
//返回指定位置的元素
public Student get(int index){
return list[index];
}
//返回集合中当前元素的个数
public int size(){
return count;
}
public String to String(){
String msg = "";
for(int i = 0;i<list.length&&list[i]!=null;i++){
msg = msg + list[i].toString()+"\n";
}
return msg;
}
}
#第八次课:Arrays of Objects
####
对象数组
\color{#FF0000}{对象数组}
对象数组
●所谓对象数组,就是包含了一组相关的对象,但是在对象数组的使用中读者一定要清楚一点,数组一定要先开辟空间,但是因为其是引用数据类型,所以数组里面的每一个对象都是null值,则在使用的时候数组中的每一个对象必须分别进行实例化操作。
●对象数组的声明:
♦类 对象数组名称[] new 类[数组长度];
示例:
class Person{
private String name; //姓名属性
public Person(String name){ //通过构造方法设置内容
this.name = name; //为姓名赋值
}
public String getName(){ //取得姓名
return this.name;
}
}
public class ObjectArrayDemo01{
public static void main(String args[]){
Person per[] = new Person[3]; //声明一个对象数组,里面有三个对象
System.out.println("------数组声明-------");
for(int x = 0;x < per.length;x++){
System.out.print(per+"、")//循环输出
}
per[0] = new Person("张三");//实例化第一个元素
per[1] = new Person("李四");//实例化第二个元素
per[2] = new Person("王五");//实例化第三个元素
System.out.println("------对象实例化-------");
for(int x = 0;x < per.length;x++){
System.out.print(per[x].getName() + "、");
}
}
}
■So far,we have dealt with arrays of primitive data types(int double) values.
●Arrays to store objects can also be created.
Using the Car class,we can declare arrays to hold object references,as follows:
Car[] cars = new Car[MAX_CARS];//MAX_CARS is 10
●Then we can add Car references to the cars array as follows:
cars[0] = new Car("OOP101","Ford Falcon","Perth",35000);
cars[1] = new Car("OOP102","Nissan Cedric","Perth",2000);
cars[2] = new Car("GUI123","Ford Falcon","Perth",29000);
●The array can then be iterated in a loop as follows:
for(int i = 0;i < 3;i++)
System.out.println(car[i].getRego());
;
■With arrays of objects,each array element holds a reference to the object,not the object itself.
●Items can be added to and deleted from an array as the program is run.
●The logical size of the array,is the number of items currently stored.
●The maximum capacity of the array as given by its length property.
●Here,the capacity is 10,and the size is 3.
●For elements 3-9 the reference is by default set to null.
■In the preceding declarations,only three cars are stored in the array.
●if the preceding for loop were inadvertently coded as:
for(int i =0;i < cars.length;i++)
System.out.println(Cars[i].getRego());
●The output world print the registration number of the three cars and then terminate with a run-time exception:
OOP101
OOP102
GUI123
Exception in thread “main”
java.lang.NullPointerException
at
CarArrayDemo.main(CarArrayDemo.java:15)
■At this point cars[3] has no logical meaning - there is nothing there except null,and no object exists at that position.
●To guard against this,the for loop can be modified as:
for(int i = 0;i < cars.length && cars[i] != null;i++)//stop the loop when a null value is accessed.
System.out.println(cars[i].getRego());
collections(1)
■when grouping objects together,we end up with a collection.
●Most applications involve a collection of one or more objects.
●In the previous chapter,when processing the payroll,we had no way of storing individual Employee objects.
●With a collection of objects,common operations include:
-Creating the collection.
-Adding and removing items to/from the collection.
-travering the collection.
collections(2)
■There are a number of strategies for managing a collection,that include:
-Using a raw array,as with Car[] cars array.
-Using a class that acts as a container and providdes the code to manage the collection.
●By using a collection class,it is responsible for maintaining the collection.
●We could write our own collection class,or use one that is already provided in the Java API,such as ArrayList class.
●The ArrayList class has a number of methods,including:
- add():Adds an object at the end of the items in the list.
- indexOf():Searches for an object at the end of the - items and return its index.
- get():Gets an object at a specified index.
- size():Returns the number of elements stored in the array.
collections(3)
■In this section we will develop the CarList class to store a list of Car refer.
●It emulates a small subset of the methods in the ArrayList class.
●The CarList class helps in understanding how the ArrayList class works.
●In the CarList class,the array is a privatefield that is set in the constructor:
public class CarList{
private int count;//Number of cars in the yard
private Car[] cars;//The car database
public CarList(int maxLength){
cars = new Car[maxLength];
}
}
...
Adding to the List(1)
When adding to our list of cars,we need to ensure that:
●a non-existent car is not added to the list(a null car) and
●the size of the array is not exceeded(the container is not overfilled).
public boolean add(Car car){
if(car == null){
return false;//Can't add a null car
}
if(cars.length<count)
return false;//Array is full
cars[count++]=car;//add car to end of array
}
Searching the List(1)
■Arrays can be searched to determine whether they contain a certain item.
●The simplest way to search an array is sequentially:
-by examining each element of an array,starting at the first element,
-continuing one after another until either the search item is located,
-or the end of array is reached,-the search item is not found.
●if the element is found:
-the index of the element is returned,(hence the name,indexOf())
-otherwise -1 as an invalid array index is returned.
Searching the List(2)
■The indexOf() method uses sequential search for an item in an array:
public int indexOf(String regoToFind){
for(int index = 0;index<cars.length;index++){
if(cars[index].getRego().equals(regoToFind))
return index; //Rego found at index;
}
return -1;//Rego not found
}
Searching the List(3)
■the indexOf() method can be invoked as:
index = carList.indexOf(findRego);//Find rego in list
if(0 <= index){
car = carList.get(index);//Retrieve car from list
printCarDetails(car);//Print its details
}
else
System.out.println("Vehicle:"+findRego+"not found.");
Traversing Lists(1)
■Since our array is locked up inside the CarList container,we need to use the get() method to retrieve each object:
for(int i =0;i<fleetList.size();i++){
car = fleetList.get(i);
System.out.printf(" %-10s %-10s\n",car.getRego(),car.getLocation());
}
实例:
Student.java
class Student{
private String id;
private String name;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@
public String toString() {
return "Student{id = " + id + ", name = " + name + "}";
}
}
学生集合类StudentList.java
//自行实现的学生集合类,封装集合的创建、添加、删除、查找、获取大小、遍历等操作
public class StudentList {
//成员变量
Student list[];
int count;//集合中目前元素的个数
//成员方法
//创建:通过构造方法来实现
public StudentList(int max){
list = new Student[max];//数组初始化
count = 0;//集合中的元素个数
}
//讲一个对象添加到集合中,返回是否成功(失败:参数student为null或者数组满了)
public boolean add(Student student){
if(student == null){
return false; //参数为null,不能添加
}
//数组已满,不能添加
if(list.length <= count){
return false;//数组已满,不能添加
}
list[count]=student;
count++;
return true;
}
//删除操作,:删除指定位置的元素(index不在范围内,会失败)
public boolean remove(int index){
if(index>=count || index<0)
return false;
list[index] = null;
return true;
}
//接对象的某个字段(一般是关键字段)来查找,返回找到的对象在数组中首次出现的位置。如果没找到,则返回-1
public int indexOf(String id){
for(int i=0;i< list.length && list[i] != null;i++)//遍历条件
{
if(list[i].getId().equals(id))
return i;
}
return -1;//未找到
}
//返回指定位置的元素
public Student get(int index){
return list[index];
}
//返回集合中当前元素的个数
public int size(){
return count;
}
public String to String(){
String msg = "";
for(int i = 0;i<list.length&&list[i]!=null;i++){
msg = msg + list[i].toString()+"\n";
}
return msg;
}
}