用于打印客户对象的阵列列表

时间:2016-02-03 18:46:36

标签: java arraylist

如何使用Customer类型的数组列表(具有2个子类,非成员和成员)来使用比较打印出所有客户对象?换句话说,我想检查某个索引处的数组列表,并检查它是否是非成员或成员对象并相应地打印输出。这是我的代码:

ArrayList<Customer> customerList = new ArrayList<Customer>();

for(int i = 0; i < customerList.size(); i++)
{
    if(customerList.get(i) == // nonmember)                     
    {
        // want to use toString in NonMemberCustomer class
    }
    else // member
    {       
        // use toString in MemberCustomer class to print output.
    }
}
public String toString()    
{
    return "\nMember Customer:" + super.toString() +
           "Collected Points:\t" + pointsCollected + "\n\n";
}
public String toString()
{
    return "NonMember Customer:" + super.toString() +
           "Visit Fee:\t\t" + visitFee + "\n\n";
}

1 个答案:

答案 0 :(得分:1)

使用Customer作为参数类型声明您的arraylist:

// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();

其次,您不需要if/else语句来打印对象的相应toString();只需覆盖每个课程中的toString()方法&amp; polymorphism将从那里拿走它。

for(int i =0; i < customerList.size();i++) {
    // Implicit call to the toString() method
    System.out.println(customerList.get(i)); 
}

课程:(例如)

class Customer {
    // properties & methods

    @Override
    public String toString() {
        System.out.println("The customer's toString !");
    }
}

class Member extends Customer {
    // properties & methods

    @Override
    public String toString() {
        System.out.println("The member's toString !");
    }
}

class NonMember extends Customer {
    // properties & methods

    @Override
    public String toString() {
        System.out.println("The nonmember's toString !");
    }
}