黑马程序员技术交流社区

标题: 继承实现动态数组 [打印本页]

作者: lvjayj    时间: 2013-8-12 20:12
标题: 继承实现动态数组
范例------继承的应用,实现数组的动态大写、元素排序、元素反转
  1. class ReverseArray
  2. {
  3. private int temp[];  // 声明一个数组,这个数组的大写由外部程序决定
  4. private int foot;  // 记录数组元素的下标
  5. public ReverseArray(int len)  // 数组的大小由外部决定
  6. {
  7.   if(len > 0)  // 判断传入(接收)的数值是否大于 0
  8.   {
  9.    this.temp = new int[len];  // 根据接收到数值,为该数组开辟指定大小的空间
  10.   }
  11.   else
  12.   {
  13.    this.temp = new int[1];  // 最小维持一个元素的空间
  14.   }
  15. }
  16. public boolean add(int i)  
  17. {
  18.   if(this.foot < this.temp.length)  // 判断数组是否已经满员
  19.   {
  20.    this.temp[foot] = i;  // 没有满员则继续添加
  21.    foot++;  // 修改下标
  22.    return true;  // 添加新成员成功
  23.   }
  24.   else
  25.   {
  26.    return false; // 数组已经满员,不可以继续添加新成员
  27.   }
  28. }
  29. public int[] getArray()
  30. {
  31.   return this.temp;  // 返回当前数组
  32. }
  33. }
  34. public class ArrayDemo
  35. {
  36. public static void main(String []args)
  37. {
  38.   ReverseArray a = null;  // 声明反转类的对象
  39.   a = new ReverseArray(5); // 实例化反转类对象
  40.   System.out.print(a.add(23) + "\t");  // 添加新成员
  41.   System.out.print(a.add(21) + "\t");  // 添加新成员
  42.   System.out.print(a.add(2) + "\t");  // 添加新成员
  43.   System.out.print(a.add(6) + "\t");  // 添加新成员
  44.   System.out.print(a.add(99) + "\t");  // 添加新成员
  45.   System.out.print(a.add(36) + "\t\n");  // 添加新成员
  46.   print(a.getArray());  // 输出数组的元素
  47. }
  48. public static void print(int x[])
  49. {
  50.   for(int i = 0; i < x.length; i++)
  51.   {
  52.    System.out.print(x[i] + "、");
  53.   }
  54. }
  55. }
复制代码

作者: 许庭洲    时间: 2013-9-25 08:13
值得学习ing!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2