1、ArrayList是一个动态数组,简单来说就是数组长度可以发生改变
2、ArrayList可以灵活的在原有数组中做增加,删除,插入方法
3、实例:
public class Add {
void AddMessage(ArrayList<Thushus> list)
{
Scanner in=new Scanner(System.in);
System.out.println("请输入名字");
String name=in.nextLine();
System.out.println("请输入产地");
String chandi=in.nextLine();
System.out.println("请输入价格");
double price=in.nextDouble();
Scanner ij = new Scanner(System.in);
System.out.println("请输入类型");
String type=ij.nextLine();
Thushus thushus=new Thushus(name,chandi,price,type);
list.add(thushus);
}
}
/*重新写一个方法Add
* void AddMesssage(ArrayList<构造对象名:Thushus> list)
* {
* Thushus thushus = new Thushus(name,chandi,price,type);
* list.add(thushus);
* }
*/
4、与普通数组进行增加操作对比
void zeng1(){
books[1] = new Thushus("可乐", "湖南", 3.50, "小杯");
books[2] = new Thushus("雪碧", "江西", 4.50, "小杯");
books[3] = new Thushus("奶茶", "江苏", 9.50, "小杯");
Scanner in = new Scanner(System.in);
System.out.print("\n请输入你要增加的商品名称:");
String a1=in.nextLine();
System.out.print("\n请输入你要增加的商品产地:");
String a2=in.nextLine();
System.out.print("\n请输入你要增加的商品价格:");
double a3=in.nextDouble();
System.out.print("\n请输入你要增加的商品类型:");
Scanner ij = new Scanner(System.in);
String a4=ij.nextLine();
books[++num] = new Thushus(a1, a2, a3, a4);
System.out.println("\n商品展示:");
for(int i=1;i<=num;i++){
System.out.println(books[i].getName()+"\t"+books[i].getChandi()+"\t"+books[i].getPrice()+"元"+"\t"+books[i].getType());
}
}
}
/*ArrayList<Thushus> list = new ArrayList<>();
* Add add = new Add();
* add.AddMessage(list);
* for(int i=0;i<2;i++)
* {
* System.out.println(list.get(i).getName()+"\t"+list.get(i).getChandi()+"\t"+list.get(i).getPrice()+"\t"+list.get(i).getType());
* }
*/