Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while creating LinkedList of LInkedLists

I am trying to create a LinkedList of LinkedLists in Java.

The following code segment is giving an error. I am using java 11 and util.List

No idea why I am getting this error..

N = in.read();
List<List<Integer>> L;
L = new LinkedList<>();
for( i = 0;i<N;i++) L.add(new LinkedList<>());

It gives the following errors:

A.java:25: error: cannot infer type arguments for LinkedList
            L = new LinkedList<>();
                              ^
  reason: cannot use '<>' with non-generic class LinkedList
A.java:26: error: cannot infer type arguments for LinkedList
            for( i = 0;i<N;i++) L.add(new LinkedList<>());
                                                    ^
  reason: cannot use '<>' with non-generic class LinkedList

How should I go on resolving this?


Okay, so just to test I created a dummy class just to create LinkedList of LinkedLists. Here is the full program:

import java.util.*;
class Dummy
{
    public static void main(String[] args) 
    {
        List<List<Integer>> L;
        L = new LinkedList<>();
        for(int i = 0;i<10;i++) L.add(new LinkedList<>());    
    }
}

Again, these errors:

A.java:7: error: cannot infer type arguments for LinkedList
        L = new LinkedList<>();
                          ^
  reason: cannot use '<>' with non-generic class LinkedList
A.java:8: error: cannot infer type arguments for LinkedList
        for(int i = 0;i<10;i++) L.add(new LinkedList<>());    
                                                    ^
  reason: cannot use '<>' with non-generic class LinkedList

Edit: Okay, works fine when I use import java.util.List and import java.util.linkedList instead of import java.util.*

As pointed out in the comments there is probably some issue with my build path

like image 371
Little_idiot Avatar asked Nov 07 '22 12:11

Little_idiot


1 Answers

I've tried your example using java7 and using java8, and it gives me the same error as you are seeing for java7, but works for me for java8.

Why it doesn't work for java7 will have to do with limitations of type inference in that version of the compiler.

I would expect java11 to work at least as well as java8 (which is to say, the code should compile using java11). Can you double check your compiler settings? You may be using a java11 compiler, but may have set it to generate code using the java7 rules.

Here is the version of the code that I tested:

import java.util.List;
import java.util.LinkedList;

public class TypeTest {
    private static final int STORAGE_SIZE = 10;

    private static final List<List<Integer>> storage = new LinkedList<>();

    static {
        for ( int elementNo = 0; elementNo < STORAGE_SIZE; elementNo++ ) {
            storage.add( new LinkedList<>() );
        }
    }
}
like image 67
Thomas Bitonti Avatar answered Nov 12 '22 11:11

Thomas Bitonti