String[] myArray = new String[2];
int[] intArray = new int[2];
// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};
ArrayList<int> numbers = new ArrayList<int>();
^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
^ perfectly valid
另外,你可以使用自己的对象,这是我创建的Monster对象
public class Monster {
String name = null;
String location = null;
int age = 0;
public Monster(String name, String loc, int age) {
this.name = name;
this.loc = location;
this.age = age;
}
public void printDetails() {
System.out.println(name + " is from " + location +
" and is " + age + " old.");
}
}
public class Main {
ArrayList<Monster> myMonsters = new ArrayList<Monster>();
public Main() {
Monster yetti = new Monster("Yetti", "The Mountains", 77);
Monster lochness = new Monster("Lochness Monster", "Scotland", 20);
myMonsters.add(yetti); // < added Yetti to our list
myMonsters.add(lochness); // < added Lochness to our list
for (Monster m : myMonsters) {
m.printDetails();
}
}
public static void main(String[] args) {
new Main();
}
}
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
如果使用其他方式,如上文所述,即:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
虽然这段代码工作正常,但它有不安全或未经检查的操作,这会导致错误
# 3 楼答案
我猜你对类型的参数化感到困惑:
// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>();
// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();
# 1 楼答案
没有更多关于问题的细节,我将回答问题的标题
创建一个^{} :
创建一个^{} :
这意味着,创建一个
ArrayList
的String
和Integer
对象。您不能使用int
,因为这是一个primitive data types,请参阅链接以获取基本数据类型的列表创建一个^{} :
创建一个^{} :(使用LinkedList)
与
ArrayList
一样,这个声明意味着创建Queue
个String
和Integer
对象更新:
对于你在另一个给定答案中的评论
我们使用
String
只是作为一个纯粹的例子,但您可以添加任何其他对象,但主要的一点是,您使用对象而不是原始类型。每个基本数据类型都有自己的primitive wrapper class,请参见链接以获取基本数据类型的包装类列表我已经发布了一些链接来解释两者之间的区别,但下面是一个基本类型列表
byte
short
char
int
long
boolean
double
float
也就是说,你不能像这样做
ArrayList
另外,你可以使用自己的对象,这是我创建的
Monster
对象这里我们有一个
Monster
对象,但现在在我们的Main.java
类中,我们想保留我们创建的所有Monster
的记录,所以让我们将它们添加到ArrayList
(我帮我女朋友的弟弟玩了一个Java游戏,他也不得不做一些类似的事情,但我希望这个例子能得到很好的演示)
# 2 楼答案
只是对这篇文章的第一个答案做了一个小小的更正
即使对于Stack,如果使用来自Javautil包的Stack,也需要使用泛型创建新对象
如果使用其他方式,如上文所述,即:
虽然这段代码工作正常,但它有不安全或未经检查的操作,这会导致错误
# 3 楼答案
我猜你对类型的参数化感到困惑: