在编程中常常会遇到需要动态操纵数组,比如在运行时增加和删除数组元素,而且有时在编译时又不想确定数组大小希望它可以动态伸缩,在java中解决这一问题的方法是使用java.util包中的arraylist类,该类提供了许多的方法可以实现数组的动态操控,我是一名java初学者在这里只想把自己的学习成果与大家分享,以后我还会写很多关于java的文章,希望大家多给意见!空话不多说,我们要注重实效来看个例子吧!(在win2000下调试通过)
import java.util.*;
public class arraylisttest
{
public static void main(string[] args)
{
arraylist staff = new arraylist();
employee emp = new employee("ivan",60000,1984,10,6);
employee emp1 = new employee("jack",35000,1982,8,14);
staff.add(new employee("carl cracker", 75000, 1987, 12, 15));
staff.add(new employee("harry hacker", 50000, 1989, 10, 15));
staff.add(new employee("tony tester", 40000, 1990, 12, 15));
//使用该方法将对象添加到列表的指定位置,而不会覆盖原有 值,原有值会自动往下移动一格
staff.add(1, emp);
//使用该方法将对象添加到列表的指定位置,会覆盖原有值
staff.set(2,emp1);
//使用该方法将指定位置的对象从列表中删除,其后的对象将自动往上移一个同时调整列表大小
staff.remove(2);
//size()返回当前列表中元素的个数
system.out.println(staff.size());
for (int i = 0; i < staff.size(); i++)
{
employee e = (employee)staff.get(i);
e.raisesalary(5);
}
for (int i = 0; i < staff.size(); i++)
{
employee e = (employee)staff.get(i);
system.out.println(e);
}
}
}
class employee
{
public employee(string n, double s, int year, int month, int day)
{
name = n;
salary = s;
gregoriancalendar calendar =
new gregoriancalendar(year, month - 1, day);
hireday = calendar.gettime();
}
public string getname()
{
return name;
}
public double getsalary()
{
return salary;
}
public date gethireday()
{
return hireday;
}
public void raisesalary(double bypercent)
{
double raise = salary * bypercent / 100;
salary += raise;
}
public string tostring()
{
return getclass().getname()
+ "[name="+ name
+ ",salary="+ salary
+",hireday="+ hireday
+"]";
}
private string name;
private double salary;
private date hireday;
}
闽公网安备 35060202000074号