ArrayList 的不安全或未经检查的操作 [英] Unsafe or unchecked operations for ArrayList

查看:29
本文介绍了ArrayList 的不安全或未经检查的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被指派制作一个程序,该程序可以获取 0-25 之间的 100 个随机整数并将它们存储在一个数组中.然后我必须调用 2 种方法来分割偶数和赔率(非常典型).所以我尝试了 ArrayList 的东西(我刚刚学会了它)并且它看起来很好(我正在关注教程和在线内容),直到我遇到这个:Unit8.java 使用未经检查或不安全的操作

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

我的代码是这样的:

    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]);
    }
}

}

错误发生在:even.add(e[y]);odd.add(o[z]);

请帮我解决这个问题,我已尽力使其清晰易懂.

Please Help me out with this, I've tried my best to make it clear and easy to understand.

推荐答案

这是因为您将 ArrayListraw type 一起使用.您正在向其添加特定类型.

This is because you are using ArrayList with raw type. And you are adding a specific type to it.

原始类型 ArrayList 需要 Object 类型的元素.如果您添加任何其他类型,那么 Compiler 将无法确切知道您存储的是什么类型.因此,它为您提供未经检查或不安全的操作,以警告您可能做错了什么.

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.

你最好创建一个 Generic ArrayList:-

You should better create a Generic ArrayList:-

List<Integer> evenNumbers = new ArrayList<Integer>();

另外,在您的 method 签名中更改它:-

Also, change it in your method signature: -

public static void evensDivider (int[] e, List<Integer> evenNumbers)

PS: - 如果你有 interface type 的引用,你应该总是有一个引用.我的意思是使用 List 代替 ArrayList

PS: - You should always have a reference of interface type if you have one. I mean use List in place of ArrayList

这篇关于ArrayList 的不安全或未经检查的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆