英文:
Get two notes in Pair class in java while compiling code
问题
我编写了代码来解释 Java 中的 Pair 类。我得到了我预期的输出,但在编译时我收到了一个注意。
注意:MyArrayList.java 使用了未经检查或不安全的操作。
注意:重新编译时请使用 -Xlint:unchecked 以获取详细信息。
我的代码是:
import java.util.ArrayList;
class MyArrayList
{
public static void main(String[] args)
{
Pair<String, Integer> p1 = new Pair("Shubham", 1804017);
Pair<Integer, String> p2 = new Pair(1804025,"Sanket");
Pair<Boolean, String> p3 = new Pair(true,"Sanket");
p1.getInfo();
p2.getInfo();
p3.getInfo();
}
}
class Pair<X,Y>
{
X x;
Y y;
public Pair(X x,Y y)
{
this.x = x;
this.y = y;
}
public void getInfo()
{
System.out.println(x+" "+y);
}
}
那么这个注意是什么意思,我们能避免它吗?
英文:
I write code to clear the doubt about Pair class in java. I got my output what I expected but while compiling I got a note.
Note: MyArrayList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
My Code is
import java.util.ArrayList;
class MyArrayList
{
public static void main(String[] args)
{
Pair<String, Integer> p1 = new Pair("Shubham", 1804017);
Pair<Integer, String> p2 = new Pair(1804025,"Sanket");
Pair<Boolean, String> p3 = new Pair(true,"Sanket");
p1.getInfo();
p2.getInfo();
p3.getInfo();
}
}
class Pair<X,Y>
{
X x;
Y y;
public Pair(X x,Y y)
{
this.x = x;
this.y = y;
}
public void getInfo()
{
System.out.println(x+" "+y);
}
}
So What is that note and can we avoid it?
答案1
得分: 1
只需在此处使用钻石操作符。
Pair<String, Integer> p1 = new Pair<>("Shubham", 1804017);
Pair<Integer, String> p2 = new Pair<>(1804025, "Sanket");
Pair<Boolean, String> p3 = new Pair<>(true, "Sanket");
英文:
Just use the diamond operator here.
Pair<String, Integer> p1 = new Pair<>("Shubham", 1804017);
Pair<Integer, String> p2 = new Pair<>(1804025,"Sanket");
Pair<Boolean, String> p3 = new Pair<>(true,"Sanket");
See also What is the point of the diamond operator (<>) in Java 7?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论