本帖最后由 rose_xiaomei 于 2015-6-13 23:13 编辑
今天练习Arraylist,在MyEclipse写到毕老师那么段代码,但是一直出现黄色的警告,程序也没有得到预期的效果,求大神赐教。警告提示如下
Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized
- package ListTest;
- import java.util.*;
- //将自定义对象作为元素储存在Arraylist数组中,并去除重复元素
-
- //定义一个Person类 对外提供Get Set方法
- class Person{
- private String name;
- private int age;
- Person(String name,int age){
- this.name=name;
- this.age=age;
- }
- public String getName (){
- return name;
- }
- public int getAge(){
- return age;
- }
- //提供对象比较的Eqeals方法
- public boolean equals(Object obj){
- if (!(obj instanceof Person) ){
- return false;
- }
- Person p = (Person)obj;
- return this.name.equals(p.name) && this.age==p.age;
- }
- }
- public class ArratListDemo {
-
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
-
- ArrayList al = new ArrayList();
- al.add(new Person("java01", 1));// al.add("java01",1) ==Object obj = new Person("java01", 1);向上提升,在存储时候编译错误 Obj中没有.getname()
- al.add(new Person("java02", 2));
- al.add(new Person("java03", 3));
- al.add(new Person("java04", 4));
- al.add(new Person("java01", 1));
-
- al=singleElement(al);
-
- //打印姓名年龄
- Iterator it = al.iterator();
- while (it.hasNext()) {
- //Object obj = it.next();
- //Person p = (Person) obj;
- Person p = (Person)it.next();
- sop("name :"+p.getName()+"---Age :"+p.getAge());
- }
- }
- //定义去除重复元素方法
- public static ArrayList singleElement(ArrayList al)
- {
- //定义容器
- ArrayList newal = new ArrayList();
- Iterator it= al.iterator();
- while (it.hasNext()) {
- Object obj = it.next();
- if (!newal.equals(obj)) {
- newal.add(obj);
- }
- }
- return newal;
- }
- }
复制代码 |
|