Search code examples
javalistarraylistabstract-data-type

Changing from List to ArrayList removes the error "List is an abstract and can not be instantiated?


Well, I'm new to List I've always worked with Arrays, now I'm writing a program where I cannot tell the size of the array before it's creation so I'm using List. The thing is that I've a method that returns a List of none repeating digits.

Here is my method:

public static List<Integer> arrayOfNoneRepeatingDigits(int limit) {

List<Integer> list = new ArrayList<Integer>();

for(int i = 0; i < limit; i++){
        boolean ignore = false;
        for(int j = i; j > 0; j/=10){
            if(ignore == true) break;
            for(int k = j/10; k > 0; k/=10){
                if(j%10 == k%10){
                    ignore = true;
                    break;                        
                    }                    
                }               
            }
        if(ignore == false)list.add(i);                
        }    
return list;    
} 

First my method datatype was an Array but after I changed it to List this line of code gave an error:

List<Integer> list = new List<Integer>();

I've searched online and It turned out that I should replace List with ArrayList. I did it and the error is gone now but I don't know why.


Solution

  • Interfaces cannot be instantiated, so no new List<Integer> stuff. Interfaces's methods don't have implementations. The implementations of those methods are in the subclasses. ArrayList is one of the subclasses of List so that's why you can use your first code snippet.

    If you write new List<Integer>, it doesn't make sense. Because List's methods don't have implementations so when you call the add method, how would the compiler know what implementation is in the method?