【问题标题】:Uses unchecked or unsafe operations, recompile with -Xlint使用未经检查或不安全的操作,使用 -Xlint 重新编译
【发布时间】:2013-10-13 22:46:44
【问题描述】:

我已经处理这个问题一周了,虽然我找到了一些答案,但似乎没有一个能解决我程序的问题。

我不断收到这条消息:

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

代码如下:

import java.util.*;
public class Triangle
{
   public double a;
   public double b;
   private double c;
   private ArrayList btsarr;

   private static int numMade = 0;

   public Triangle()
   {
      this.a = 3;
      this.b = 4;
      this.c = 5;
      this.btsarr = new ArrayList();

      this.btsarr.add(this.c + "");   //adding it as a String object
      Triangle.numMade++;
   }

   public Triangle(double x1, double x2, double x3)
   {
     this.a = x1;   //specs say no data validation necessary on parameters
     this.b = x2;
     this.c = x3;
     this.btsarr = new ArrayList();

     this.btsarr.add(this.c + "");
     Triangle.numMade++;
   }

   public void setC(double x)
   {
      if (x <= 0)
      {
         System.out.println("Illegal, can't set c to 0 or negative");
      }
      else
      {
        this.c = x;
        this.btsarr.add(this.c + "");
      }
    }

    public double getC()
    {   
      return this.c;
    }   

    public void showAllCs()
    {
      System.out.println(this.btsarr);
    }

    public boolean isRightTriangle()
    {
      if (this.a*this.a + this.b*this.b == this.c*this.c)
        return true;
      else
        return false;
    }

    public static int getNumMade()
    {
      return Triangle.numMade;
    }   
}

感谢您的任何帮助,谢谢!

【问题讨论】:

  • 阅读 Generics 上的 Java 教程以获得一些基本帮助。

标签: java class


【解决方案1】:

问题在于您没有为 ArrayList 指定类型,因此没有编译时检查是否将整数插入到 String ArrayList 中。由于这将是“不安全的操作”,因此您会收到警告。

要修复,请将private ArrayList btsarr; 替换为private ArrayList&lt;String&gt; btsarr; 并将this.btsarr = new ArrayList(); 替换为this.btsarr = new ArrayList&lt;String&gt;();

一般来说,您应该在实例化它们时指定您希望 ArrayList 和 HashMap(或任何其他 Java 集合)等对象的类型。

【讨论】:

    【解决方案2】:

    这些只是警告,伙计。编译成功。 您可以毫无问题地运行您的程序。

    如果您想禁止此类警告,请使用以下注释。

    @SuppressWarnings("unchecked") //above the method definition.
    

    【讨论】:

    • 警告不应该表明某些时候可能会出错吗?如果没有后果,那么为什么会记录警告?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多