Reputation: 13
I am working on a minecraft mod. The id system for EntityC4 is not working. The code is
public static List C4 = new ArrayList();
public static EntityC4 getitemfromnumber(int num)
{
EntityC4 entity = (EntityC4)C4.get(num);
return entity;
}
public static void createdetonater(EntityC4 c4, int num)
{
C4.add(num, c4);
}
public static int getnum(){
int num = 0;
for(boolean a = true; a != false;){
EntityC4 c = (EntityC4)C4.get(num);
System.out.print("current num : " + num);
if(c != null)
{
a = false;
}else{
System.out.print("entity " + num + " is null" );
num++;
}
}
return num;
}
And when I use getnum() an error shows up that says
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
EDIT:Ty and the loop was supposed the first non-existent space in the list.
Upvotes: 1
Views: 6312
Reputation: 7242
If you rewrite your loop to use a counter then it will avoid this error. I am not sure exactly what your code is trying to do though (return first non-null instance?), so the loop below may be incorrect.
If you are trying to store a map of ID to entity, then you should probably use a HashMap<Integer,EntityC4> instead.
for(int num = 0; num < C4.size(); num++)
{
EntityC4 c = (EntityC4)C4.get(num);
System.out.print("current num : " + num);
if(c != null)
{
return num;
} else
{
System.out.print("entity " + num + " is null" );
}
}
// throw an exception or whatever else your code should do here...
Upvotes: 0
Reputation: 4167
Your error message tells you everything: you're trying to get the zeroth element from a list that has no elements. You probably need to add something to C4
,
Upvotes: 0
Reputation: 20323
Your error is coming from
EntityC4 c = (EntityC4)C4.get(num);
which states your C4
is empty, you would like to do a not null
and notEmpty
check on your list.
In order to check the reason why C4
is empty do a trace on createdetonater
and see where its being called.
Upvotes: 1
Reputation: 4941
C4
is obviously empty if you just call getNum()
, thus the exception saying that the index you are accessing doesn't exist.
You might want to pre-populate the list by calling createdetonater(..)
?
Upvotes: 1
Reputation: 36621
You create a new ArrayList C4
, you never put anything in the List
, and then you ask it for the element at index 0
. This element does not exists since the List is still empty, and it throws an exception.
You can avoid this exception by adjusting your method
public static EntityC4 getitemfromnumber(int num)
{
EntityC4 entity = null;
if ( num >=0 && num < C4.size ){
entity = (EntityC4)C4.get(num);
}
return entity;
}
This will avoid the exception, but you will get stuck in your loop since you never find the element (which isn't available in the list)
Upvotes: 5