黑马程序员技术交流社区
标题:
继承实现动态数组
[打印本页]
作者:
lvjayj
时间:
2013-8-12 20:12
标题:
继承实现动态数组
范例------继承的应用,实现数组的动态大写、元素排序、元素反转
class ReverseArray
{
private int temp[]; // 声明一个数组,这个数组的大写由外部程序决定
private int foot; // 记录数组元素的下标
public ReverseArray(int len) // 数组的大小由外部决定
{
if(len > 0) // 判断传入(接收)的数值是否大于 0
{
this.temp = new int[len]; // 根据接收到数值,为该数组开辟指定大小的空间
}
else
{
this.temp = new int[1]; // 最小维持一个元素的空间
}
}
public boolean add(int i)
{
if(this.foot < this.temp.length) // 判断数组是否已经满员
{
this.temp[foot] = i; // 没有满员则继续添加
foot++; // 修改下标
return true; // 添加新成员成功
}
else
{
return false; // 数组已经满员,不可以继续添加新成员
}
}
public int[] getArray()
{
return this.temp; // 返回当前数组
}
}
public class ArrayDemo
{
public static void main(String []args)
{
ReverseArray a = null; // 声明反转类的对象
a = new ReverseArray(5); // 实例化反转类对象
System.out.print(a.add(23) + "\t"); // 添加新成员
System.out.print(a.add(21) + "\t"); // 添加新成员
System.out.print(a.add(2) + "\t"); // 添加新成员
System.out.print(a.add(6) + "\t"); // 添加新成员
System.out.print(a.add(99) + "\t"); // 添加新成员
System.out.print(a.add(36) + "\t\n"); // 添加新成员
print(a.getArray()); // 输出数组的元素
}
public static void print(int x[])
{
for(int i = 0; i < x.length; i++)
{
System.out.print(x[i] + "、");
}
}
}
复制代码
作者:
许庭洲
时间:
2013-9-25 08:13
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2