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.
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