user5304122
user5304122

Reputation:

compilation error in generic list

When I use the below code , I do not get compilation error

import java.util.ArrayList;


public class C {

    public static void main(String[] args) {
        ArrayList <Integer> list = new ArrayList<Integer>();
        list.add(4);
        list.add(7);
        list.add(12);
        System.out.println(list);
        int sum=2;
        for (int i:list){
            sum+=i;
            System.out.println(sum);
        }
    }
}

but when I use the below code , I get error in the format of the generic List (I do not know why ):

import java.util.List;
public class C {


public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>(); // List cannot be resolved to a type
        list.add(4);
        list.add(7);
        list.add(12);
        System.out.println(list);
        int sum=2;
        for (int i:list){
            sum+=i;
            System.out.println(sum);
        }  
    }
}

How to do to fix the second code ?

Upvotes: 0

Views: 192

Answers (1)

Ghazanfar
Ghazanfar

Reputation: 1469

Add the below import statements to your code,

import java.util.ArrayList;
import java.util.List;

See this line in your code,

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

This line uses the List interface AND the ArrayList class. So, you need to have both of them imported in your file.

Upvotes: 4

Related Questions