如果将多个元素添加到arraylist,我怎么能抛出运行时异常?

问题描述 投票:-2回答:1

所以我正在尝试编写一个函数,将一个Element添加到另一个类的arraylist中。现在我的问题是,如果在此函数中添加了多个元素,我想抛出一个RuntimeException。我该如何设法做到这一点?

    public class Specialcars extends Car {

           public void addtire(Tire tire) {

             //adds element to arraylist outgoingtires in class Car
               outgoingtires.add(tire)

            //now here i want to throw a Runtime Exception if more    
            //than one tires are added 

                                                       }


                                         }
java arraylist runtimeexception
1个回答
0
投票

用户阵列而不是ArrayList。数组具有固定大小,因此您可以在实例化时限制数组的大小。如果你试图添加更多元素来修复大小的数组,它会抛出IndexOutOfBoundsException,这本质上是一个RuntimeException

© www.soinside.com 2019 - 2024. All rights reserved.