0

Here is an extremely simplyfied version of my recent project, which demonstrates the problem:

import java.util.List;
import java.util.ArrayList;
class Class{
        List<Character> l1 = new ArrayList<>();
        List<Character> l2 = new ArrayList<>();
        List getList(){
                return l1;
        };
        void setList(){
                l2.clear();
                l2.addAll(getList());
        };
}
class Main{
        public static void main(String[]args){
                Class object = new Class();
                object.setList();
        };
}

When I compile it, the compiler says:

Note: Class.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

When I take l2.addAll(getList()); away, then the compiler doesn't return that message, but obviously this screws over my project.

What are unchecked or unsafe operations and how can I fix them?

2 Answers2

1

Instead of

List getList(){

specify the type paramater, like

List<Character> getList(){

Before, you were returning a raw type, instead of a generic one.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
0

Try following the compiler's advice:

$ javac -Xlint:unchecked Class.java
Class.java:11: warning: [unchecked] unchecked method invocation: method addAll in interface List is applied to given types
                l2.addAll(getList());
                         ^
  required: Collection<? extends E>
  found: List
  where E is a type-variable:
    E extends Object declared in interface List
Class.java:11: warning: [unchecked] unchecked conversion
                l2.addAll(getList());
                                 ^
  required: Collection<? extends E>
  found:    List
  where E is a type-variable:
    E extends Object declared in interface List
2 warnings

This makes it very clear that the unchecked conversion is because you're passing a List where a Collection<? extends E> is required.

So you can fix it by changing the type of List to List<E> (or List<? extends E>); in other words, make the return type of getList() non-raw.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243