您的位置:首页 > 编程语言 > Java开发

《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 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: