《Java 编程技巧1001条》第401条:数组中存不同对象
2017-12-23 10:58
771 查看
《Java 编程技巧1001条》第10章 用数组存储数据 第401条 数组中放不同对象
401 Storing Different Objects in an Array
401 在一个数组中存放不同的对象
The arraysyou have created in the previous tips only contain a single type of object. Asit turns out, you can also create arrays that hold many different types ofobjects. The most generic array that you can declare in Java is of type Object.Every Java object is a subclass of the Object class. Within an array, you canstore any Java objects reference. However, to retrieve and use an object froman Object array, you must use the instanceof operator. The following codedemonstrates how you can store images and rectangles in a single array:前面你所创建的各种数组仅包含单种类型的对象. 当需要时,你也可以创建包含多种对象类型的数组. 在Java中,你可以声明的最根本的数组是Object型数组. 每一个Java对象是Object类的子类. 在一数组中,你可以用来存放任意的Java对象引用. 但是,为了从Object数组中抽取(retrieve)和使用(use)一个object,你必需使用instanceof函数.以下这些语句说明了怎样在单一的数组中存放图象和矩形:import java.awt.*;import java.awt.image.*;import java.applet.*; public class arrayOfObjectsApplet extendsApplet { Object array[] = new Object[4]; public void init() { array[0] = getImage(getCodeBase(), "a.gif"); array[1] = getImage(getCodeBase(), "b.gif"); array[2] = new Rectangle(0,26,26, 26); array[3] = new Rectangle(26,0,26, 26); } public void paint(Graphics g) { g.setColor(Color.black); for (int i = 0; i < array.length; i++) { if (array[i] instanceof Image) { Image img = (Image) array[i]; g.drawImage((Image)array[i],i*26,i*26,this); } else if (array[i] instanceof Rectangle) { Rectangle r = (Rectangle) array[i]; g.fillRect(r.x, r.y, r.width, r.height); } } } }
As you havelearned, Java applets use interfaces to allow one class to access the data andmethods of another. Sometimes, you will find it more convenient to create aninterface that all objects in an array implement. In this way, you can thencall the methods of the interface without having to know what the objects are.
正如你所了解的,Java应用块利用interfaces(接口)使一个类能访问另一个类的数据和方法. 有时候,你会发现建立一个接口把所有对象都放在一数组工具中将更方便.这样,你不需要知道对象是什么就可以调用接口方法. 【374-401节完】
1001 Java Programming Tips
Page
相关文章推荐
- 《Java 编程技巧1001条》 第384条: 建立对象数组..
- 《Java 编程技巧1001条》 第386条: 声明多维数组
- 《Java 编程技巧1001条》 第394条: 数组分类(排序)
- 《Java 编程技巧1001条》 第389条: 了解不平衡数组
- 《Java 编程技巧1001条》 第390条: 初始化多维数组
- 《Java 编程技巧1001条》 第400条: 使用数组复制
- 《Java 编程技巧1001条》 第382+283条: 了解数组的长度和引用
- 《Java 编程技巧1001条》 第387条: 建立多维数组
- 《Java 编程技巧1001条》 第399条:对原始类型数组使用数组复制
- 《Java 编程技巧1001条》 第388条: 遍历多维数组
- 《Java 编程技巧1001条》第391条: 在数组中查找一指定值
- 《Java 编程技巧1001条》 第381条: 给数组元素赋值
- Java编程技巧-对象的创建和销毁
- 《Java 编程技巧1001条》 第403条: 了解事件类
- 《Java 编程技巧1001条》 第404条: 了解实用方法
- 《Java 编程技巧1001条》 第405条: 使用mouseDoun方法
- JAVA数组和JAVA集合类的对象操作-Java基础-Java-编程开发
- 《Java 编程技巧1001条》 第393条: 使用2分查找
- 编程技巧系列(4)Java数组转化成String
- 【Java编程】Foreach对数组、Collection对象、Iterable对象的遍历