Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

arrays - Java ArrayList IndexOutOfBoundsException despite giving an initial capacity

When I do

ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0, 1);

Java gives me

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.set(Unknown Source)
    at HelloWorld.main(HelloWorld.java:13)

Is there an easy way I can pre-reserve the size of ArrayList and then use the indices immediately, just like arrays?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this:

ArrayList<Integer> arr = new ArrayList<Integer>(Collections.nCopies(10, 0));

This will initialize arr with 10 zero's. Then you can feel free to use the indexes immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...