Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ensureCapacity not recognized

Tags:

java

list

import java.util.*;
class A{
    public static void main(String[] args){
    }
    private List <B> bList;
    private Random generator = new Random();
    A(List<B> initialList){
        bList = new ArrayList<B> ();
        int listSize = initialList.size();
        bList.ensureCapacity(listSize);
             for (B b : initialList) {
             int bIndex = generator.nextInt(listSize);
             bList.add(bIndex , b);
        }
    }
}
class B{
}

I have been getting the error reading

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.util.List.ensureCapacity

like image 616
Kevin K Avatar asked Dec 04 '25 15:12

Kevin K


2 Answers

ensureCapacity is not a method of type List.

And yes It's a method of ArrayList,but the reference bList is a List,you should cast it to ArrayList to use that method,like this:

((ArrayList<B>) bList).ensureCapacity(listSize);
         for (B b : initialList) {
         int bIndex = generator.nextInt(listSize);
         bList.add(bIndex , b);
    }

By the way,I never invoke the method ensureCapacity of ArrayList directly in my entire program life.

like image 153
BlackJoker Avatar answered Dec 07 '25 05:12

BlackJoker


IDE's are always good to have,Time is precious if you are using any IDE to program definitely you will get a red mark on this bList.ensureCapacity(listSize); line with a message which will secure your time to find out the solution the message clearly saying that ensureCapacity(int) is undefined for List interface.

The method ensureCapacity(int) is undefined for the type List<B>

So ensureCapacity(int) method is available inside the implementation of List interface which is ArrayList, Cast your this line(bList) bList.ensureCapacity(listSize) to ((ArrayList<B>) bList).ensureCapacity(listSize);

like image 36
subodh Avatar answered Dec 07 '25 05:12

subodh