Collections.unmodifiableList理解

unmodifiable 即只读的意思,不可以修改。
现在设计一个顾客信息的customer类,不好的写法如下:

package rr;
import java.util.ArrayList;
public class Try
{
    public static void main(String[] args)
    {
        ArrayList list = new ArrayList();
        Customer s = new Customer("Tom",list);
        list.add("1234");
        list.add("2234");
        ArrayList list1 = s.getTelephone();
        list1.add("4566");
        System.out.println("the amount of Tom's telephone  = " + s.getCourses().size());
    }

    public static class Customer
    {
        private String name;
        private ArrayList telephone;
        public Customer(String name, ArrayList telephone)
        {
            this.name = name;
            this.telephone = telephone;
        }

        public ArrayList getTelephone()
        {
            return telephone;
        }
        public void setCourses(ArrayList telephone)
        {
            this.telephone = telephone;
        }
        public String getName()
        {
            return name;
        }
        public void setName(String name)
        {
            this.name = name;
        }    
    }
}

我们的本意是Tom这个顾客,他右两个电话,可是另一个列表list1居然也可以给Tom添加电话(其他的外部东西可以修改Tom信息)
测试结果

the amount of Tom's telephone  = 3

下边使用Collections.unmodifiableList

package rr;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Try
{
public static void main(String[] args){
    ArrayList list = new ArrayList();
    Customer s = new Customer("Tom", list);
    list.add("1234");
    list.add("3455");    
    List list1 = s.getPhone();

        /**
         * throws java.lang.UnsupportedOperationException
         * should replace with s.addCourse(String course)
         */
        list1.add("999"); 

        //报错
        System.out.println("the amount of phone number = " + s.getPhone().size());        
    }

    public static class Customer
    {
        private String name;
        private ArrayList phone;

        public Customer(String name, ArrayList a)
        {
            this.name = name;
            this.phone = a;
        }

        public List getPhone()
        {
            return Collections.unmodifiableList(phone);//返回的是不可以修改的phone 数组
        }

        public String getName()
        {
            return name;
        }
        public void setName(String name)
        {
            this.name = name;
        }

        public void addPhone(String phone1)
        {
            phone.add(phone1);
        }

        public String removePhone(String phone1)
        {
            boolean removed = phone.remove(phone1);

     if (removed)
     {
         return phone1;
     }
     else
     {
                return null;
     }
        }
    }
}

插曲:
1、

List<String> list1 = s.getPhone();

报错:The type List is not generic; it cannot be parameterized with arguments 。(list不是泛型)
原因:包弄错,不是import java.awt.List;应该是

参考:http://hi.baidu.com/onejava/blog/item/10388f2b77d340fae6cd4091.html

你可能感兴趣的:(软件构造)