How can I make sure the items in the list are consistent?

a good day!

I would like to ask if I have a list of items: 1,2,3,4,5 .. then I insert the replace'3 'value into' 7 'which will prompt me an error because the list is not sequential.

List<Domain> items = new ArrayList<Domain>();

      

+3


source to share


4 answers


You can override ArrayList, set and add methods to check if the set / added element is valid, and throw an IllegalArgumentException if it is not.

Why not have a collection that is always sorted.



SortedSet<Domain> items = new TreeSet<Domain>();

      

This way, your added element will always be in the right place.

0


source


Extend ArrayList method and override add()

and addAll()

,



Or Simple use Comparator

andTreeSet

0


source


If you want to get an exception when replacing an element as you described, the best way is to expand or wrap the list and override the add methods.

If all you really need is a sorted list, use one of the SortedSets .

0


source


0


source







All Articles