Unchecked or unsafe operations error with ArrayList / PrimeDirective

I thought I’d drop this in here in case anyone ran into this, because this error is so obscure!

$ javac PrimeDirective.java 
Note: PrimeDirective.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

I ran into this in the PrimeDirective exercise, which was tripping me up. It has to do with:

    ArrayList<Integer> primes = new ArrayList();

The issue here was that I wasn’t specifying the type in the instantiation. It should be:

    ArrayList<Integer> primes = new ArrayList<Integer>();

Types always mess me up! :sweat_smile: :sweat_smile: :sweat_smile:

2 Likes

You can actually leave the 2nd set of arrow brackets empty since Java 7 or so. The compiler will infer the type from the left side of the assignment.

ArrayList<Integer> primes = new ArrayList<>();

It’s funny because types are so difficult at first, but then it can be a shock after going back to weakly typed languages.

I had a similar issue and could not figure out what I was doing wrong. It turns out the error was from not declaring the type in the method declaration. It worked fine if I used the returned value in System.out.println(), but if I tried to assigned the returned ArrayList to a variable it gave me an error.

Hey, I was just wondering if you guys know what I can do to fix my problem im having here.

import java.util.ArrayList;

class PrimeDirective {

// Add your methods here:
public boolean isPrime(int number) {
if (number == 2) {
return true;
}
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
} else if (number < 2) {
return true;
}
}
}

public static void main(String args) {

PrimeDirective pd = new PrimeDirective();
int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};

System.out.println(pd.isPrime(6));

}

}

this is the code so far. It should print out false but im not getting anything displayed.
my error code is this, Looks simple I just dont get it.

PrimeDirective.java:17: error: missing return statement
}
^
1 error

you should have return true at the end of the isPrime function.
(Otherwise there could be situations where the function doesn’t return anything.)

Also

} else if (number < 2) {
    return true;
}

does not need to be inside the for-loop.

1 Like