I'm been assigned to make a program that gets 100 random integers between 0-25 and store them in an array. I then have to call upon 2 methods to split the evens and the odds (very typical). So I tried the ArrayList thing (I jut learnt it) and it seemed fine (I was following tutorial and things online) until I ran into this: Unit8.java uses unchecked or unsafe operations
My code is this:
import java.util.*;
import java.awt.*;
public class Unit8
{
public static void main (String [] args)
{
//create an array for original 100 integers
//create a 2D array for evens and odds
//split them up using 2 methods
int[] originalArray = new int[100];
ArrayList even = new ArrayList(1);
ArrayList odd = new ArrayList(1);
for (int x = 0; x < originalArray.length; x++)
{
originalArray[x] = (int)(Math.random() * 25);
}
evensDivider(originalArray, even);
oddsDivider(originalArray, odd);
}
public static void evensDivider (int[] e, ArrayList even)
{
for (int y = 0; y < e.length; y++)
{
if (e[y]%2 == 0)
even.add(e[y]);
}
System.out.println("The evens are: " + even);
}
public static void oddsDivider (int[] o, ArrayList odd)
{
for (int z = 0; z < o.length; z++)
{
if (o[z]%2 == 1)
odd.add(o[z]);
}
}
}
With the errors occurring specifically at:
even.add(e[y]);
and
odd.add(o[z]);
Please Help me out with this, I've tried my best to make it clear and easy to understand.
How to resolve warning message: uses unchecked or unsafe operations. You can resolve this warning message by using generics with Collections. In our example, we should use ArrayList<String> rather than ArrayList() . When you will compile above code, you won't get warning message anymore.
Note: Recompile with -Xlint:unchecked for details. How do I recompile with -Xlint:unchecked ? Are you compiling on the command line? If so, add the -Xlint:unchecked to the command line you're executing, just as the message indicates.
This is because you are using ArrayList
with raw type
. And you are adding a specific type to it.
Raw type ArrayList would expect element of type Object. If you add any other type, then Compiler would not know exactly what type you are storing. So, it gives you unchecked or unsafe operations
to warn you that you might be doing something wrong.
You should better create a Generic
ArrayList:-
List<Integer> evenNumbers = new ArrayList<Integer>();
Also, change it in your method
signature: -
public static void evensDivider (int[] e, List<Integer> evenNumbers)
PS: - You should always have a reference of interface type
if you have one. I mean use List
in place of ArrayList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With