Reputation: 1
I'm trying to add elements into Arraylist using non-continuous indexes, for example:
I want to add an element at index 3 first before adding any element at indexes (0,1,2). I will also fill up the indexes at 0,1,2 later.
Here's my code:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> numbers= new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
int[] x = {1,5,2,4,3,0};
System.out.println("Enter elements:"+"\n");
for(int i=0;i<x.length;i++) {
int index = x[i];
numbers.add(index, inp.nextInt());
}
I seem to get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at Test1.main(Test1.java:28)
I understand the error, but I don't seem to find a way out of this problem. Any help will be much appreciated. If at all there's another fancy data structure which allows me to do non-continuous indexing please let me know, excuse me if my questions doesn't make any sense.
Upvotes: 0
Views: 701
Reputation: 1183
Have you thought about using a Map
?
Map<Integer,Integer> myNumbers = new HashMap<>();
myNumbers.put( 4, 100 );
myNumbers.put( 2, 199 );
myNumbers.put( 1, 150 );
System.out.println( myNumbers.get( 2 ) );
There are multiple implementations of Map
, e.g. HashMap
or TreeMap
. Which one to go for, depends on your requirements, for example, if you want to store the elements in a certain order or if you don't care about the order.
In your use case the Map could be used like this:
int[] x = { 1,5,2,4,3,0 };
// Try this instead of the above array, as well:
//int[] x = { 1337, 42, 777 };
// The Map can take an (almost) unlimited number of entries and gaps between
// indices / keys (e.g. 0, 1, 7, 23) are no problem. Only elements that you
// *put* into the Map, are part of it.
Map<Integer,Integer> numbersMap = new TreeMap<>();
System.out.println( "Enter elements:\n" );
try( Scanner inp = new Scanner( System.in ) ) {
for( int i=0; i<x.length; i++ ) {
int index = x[i];
System.out.print( "Enter element " + index + ": " );
int userInput = inp.nextInt();
numbersMap.put( index, userInput );
}
}
System.out.println( "Your Map contains these entries:" );
for( Map.Entry<Integer,Integer> entry : numbersMap.entrySet() ) {
System.out.println( "Element[" + entry.getKey() + "] = " + entry.getValue() );
}
As your indices in the x
array are continuos, without gaps, zero-based and known in advance, you could use something like this in this special case, as well:
int[] x = { 1,5,2,4,3,0 };
Integer[] output = new Integer[ x.length ];
System.out.println( "Enter elements:\n" );
try( Scanner inp = new Scanner( System.in ) ) {
for( int i=0; i<x.length; i++ ) {
int index = x[i];
System.out.print( "Enter element " + index + ": " );
int userInput = inp.nextInt();
output[ index ] = userInput;
}
}
List<Integer> numbers = Arrays.asList( output );
System.out.println( numbers );
But I'd prefer the Map
approach as it's more flexible and less error-prone.
Upvotes: 3
Reputation:
You have an arraylist, but you seem to forget that you haven't set the initial size of the arraylist. The add method that you use places the value at the given index and then shifts everything over to the right, but in this case, there's no index 1. In order to do so, you should either do
List<Integer> numbers= Arrays.asList(new Integer[10]),
which will make an arrayList with 10 "indexes" which hold a value of null, or
ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));,
which will create anarrayList with 10 "indexes" each of which hold a value of 0. For more information, look at this question which you indirectly ask. Initial size for the ArrayList
Upvotes: 1