软件构造Lab2踩坑:ArrayList报错-UnsupportedOperationException的解决办法

ArrayList报错:UnsupportedOperationException的解决办法

在软件构造Lab2实验时遇到一个问题:使用list.add()函数报出如下错误:
在这里插入图片描述

首先查看简化后的报错部分的代码:

在这里插入图片描述

逐级查看源码,首先查看Arrays.asList()函数:

    /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * <p>This method also provides a convenient way to create a fixed-size
     * list initialized to contain several elements:
     * <pre>
     *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
     * </pre>
     *
     * @param <T> the class of the objects in the array
     * @param a the array by which the list will be backed
     * @return a list view of the specified array
     */
    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

可以看出返回的是Arrays私有的ArrayList类的列表,继承了AbstractList,据此继续查找,可以查找到此ArrayList定义的部分:

private static class ArrayList<E> extends AbstractList<E>

代码查找发现该类未重写add()方法,于是查看AbstractList中关于add()方法的定义:

    public boolean add(E e) {
        add(size(), e);
        return true;
    }

继续查找,发现abstractList对add()方法的定义为:

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

可以看出,Arrays.asList()返回的私有的ArrayList实际上并未实现add()方法,也就是其抛出UnsupportedOperationException的真正原因,但是定义部分的List是使用泛型接口定义的类,然而AbstractList的定义如下:

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> 

AbstractList实现了List,因此在会逃过静态代码审查的检测,我们正常情况下使用的ArrayList是java.util.ArrarList。实现了add()方法,因此可正常使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java代码实现: ```java import java.util.ArrayList; class Contact { private int contactId; private String name; private ArrayList<Phone> phoneArray = new ArrayList<Phone>(); public Contact(int contactId, String name) { this.contactId = contactId; this.name = name; } public ArrayList<Phone> getPhones() { return phoneArray; } public void addPhoneToContact(Phone aPhone) { phoneArray.add(aPhone); aPhone.setContact(this); } // getter and setter methods } class Phone { private String name; private String phoneNum; private boolean isFreqContact; private String type; private Contact aContact; public Phone(String name, String phoneNum, String type) { this.name = name; this.phoneNum = phoneNum; this.type = type; } public void setContact(Contact aContact) { this.aContact = aContact; } // getter and setter methods } public class Main { public static void main(String[] args) { // 读入联系人信息 String[] contactInfo = new String[2]; Scanner sc = new Scanner(System.in); for (int i = 0; i < 2; i++) { contactInfo[i] = sc.nextLine(); } Contact aContact = new Contact(Integer.parseInt(contactInfo[0]), contactInfo[1]); // 读入电话信息 for (int i = 0; i < 3; i++) { String[] phoneInfo = sc.nextLine().split(" "); Phone aPhone = new Phone(phoneInfo[0], phoneInfo[1], phoneInfo[2]); aContact.addPhoneToContact(aPhone); } // 输出联系人的电话信息 ArrayList<Phone> phones = aContact.getPhones(); for (Phone phone : phones) { System.out.println(phone.getName() + " " + phone.getPhoneNum() + " " + phone.getType()); } } } ``` 输入样例: ``` 123 John 12345678901 mobile 98765432109 home 13579246810 work ``` 输出样例: ``` 12345678901 mobile 98765432109 home 13579246810 work ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值