集合的概念类似于数组,但与数组又有很大不同。主要表现在:集合的长度是可以改变的,而数组一旦被创建,其长度不可改变。
import java.util.ArrayList;
public class Demo07Hero {
public static void main(String[] args) {
Hero h01 = new Hero("安妮", 20.0);
Hero h02 = new Hero("伊泽瑞尔", 90.2);
ArrayList<Hero> arr = new ArrayList<>(); // ArrayList只能使用引用数据类型,自定义类也可以
// ArrayList<E>,E指的是泛型,必须是同一数据类型
// 对于基本数据类型要先转换为包装类,int->Integer, char->Character
arr.add(h01);
arr.add(h02);
System.out.println("集合的总长度为:" + arr.size());
for (int i = 0; i < arr.size(); i++) {
Hero h = arr.get(i); // new出来的对象是开辟了内存空间的,这种直接赋予的应该是传递的地址值
System.out.println("英雄" + h.getName() + "的攻击力为" + h.getAttack() + "。");
}
}
}
/*运行结果展示:
*集合的总长度为:2
*英雄安妮的攻击力为20.0。
*英雄伊泽瑞尔的攻击力为90.2。
*/
以下是对Hero类的定义:
public class Hero {
String name;
double attack;
public Hero(String name, double attack) {
this.name = name;
this.attack = attack;
}
public Hero() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public double getAttack() {
return attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
}