码迷,mamicode.com
首页 > 编程语言 > 详细

java集合练习

时间:2017-11-01 22:57:28      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:name   stat   util   根据   代码   练习   索引   tool   list   

技术分享

 

 

import java.util.ArrayList;
import java.util.List;

public class Bank{
    private List<Customer> customers;             //customers集合
    private int numberOfCustomers;                //记录客户数量
    public Bank(){                                //构造方法,初始化customers
        customers=new ArrayList<Customer>();
    }
    public void addCustomer(String f,String l){        //方法:往customers里面添加Customer对象
        Customer p=new Customer(f,l);
        customers.add(p);
    }
    public int getNumOfCustomers(){                   //获取客户数量,即获取customers的长度
        numberOfCustomers=customers.size();
        return numberOfCustomers;
    }
    public Customer getCustomer(int index){            //根据索引取值return customers.get(index); 
  }
}
技术分享
技术分享
public class TestBanking {
    public static void main(String[] args) {
        Bank cus=new Bank(){};
        cus.addCustomer("Simms", "Jane");
        cus.addCustomer("Bryant", "Owen");
        cus.addCustomer("Soley","Tim");
        cus.addCustomer("Soley","Maria");
        for(int i=0;i<cus.getNumOfCustomers();i++){
            System.out.println("Customer "+(i+1)+" is"+" "+cus.getCustomer(i));
        }    
        System.out.println("当前客户数量="+cus.getNumOfCustomers());
        System.out.println("第二个客户是:"+cus.getCustomer(2));
    }
}

public class Customer {
    //声明私有属性
    private String firstName;
    private String lastName;
    private Account account;
    //声明构造器
    Customer(){};
    Customer(String f,String l){
        this.firstName=f;
        this.lastName=l;
    }
    //声明存取器getter/setter方法
    public String getFirstName() {                    //firstName
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {                    //lastName
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    //存取器getter/setter方法——account
    public Account getAccount() {
        return account;
    }
    public void setAccount(Account acct) {
        this.account=acct;
    }
    @Override
    public String toString() {
        return firstName + "," + lastName;
    }
}

java集合练习

标签:name   stat   util   根据   代码   练习   索引   tool   list   

原文地址:http://www.cnblogs.com/xiaobo-Linux/p/7768842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!