While executing List<String> test = new ArrayList<String>(); it raise error that list cannot resolve to a type. I am confused because most of book write the ArrayList declaration in this way List<String> test = new ArrayList<String>();
As per the OOPS methodology, code should be designed with contract/interface and not implementation. Using this approach, implementation can be changed and user of this API do not have to change their code. It makes program more maintainable.
While executing List<String> test = new ArrayList<String>(); it raise error that list cannot resolve to a type.
Are you using any jdk version below 1.5 to compile this code, as Java SE will support Generics jdk 1.5 onwards.?
The most important reason to declare the type of your variable as a List and not an ArrayList is to decouple the interface and the implementation in your program. The program only needs to know that the list is a List, it doesn't need to know what particular implementation of interface List is being used. Hiding the implementation means that you can easily change it later.
For example, you might find out later that for that particular list, a LinkedList would be more efficient than an ArrayList (these two implementations have different performance characteristics - for example, inserting elements in the middle is more efficient on a LinkedList than on an ArrayList). If your variable is declared as being a List, you would only need to change one line:
For the rest of the program, stuff is still a List.
If you would have made stuff an ArrayList, then it would be much harder to change it to a LinkedList, because there might be places in your program where ArrayList-specific methods are called on stuff.