我有一个关于对象和存储它们的初学者问题。我需要创建一个名为 GameEntry 的单独类,其中包含一个名为 scores 的属性,然后我需要将这些 GameEntry 对象存储在一个数组中。不只是任何数组,尽管它必须是带有方括号的数组:[ ]
奇怪的是,我可以使用 ArrayList
让它工作,但是使用一个简单的 Array 就像不可能完成的任务一样?谁能帮忙?
class GameEntry {
int scores;
GameEntry(int s) {
scores = s;
}
}
public class R11ScoreArray {
public static void main(String[] args) {
GameEntry[] scoreArray; // declares that scoreArray is an array of
// 'GameEntry'
scoreArray = new GameEntry[4]; // create array of 4 elements
scoreArray[0] = new GameEntry(10);
scoreArray[0] = new GameEntry(100);
scoreArray[0] = new GameEntry(1000);
scoreArray[0] = new GameEntry(10000);
for (int i = 0; i < scoreArray.length; i++) {
System.out.println(Arrays.toString(scoreArray));
}
}
}
最佳答案
解释
我认为您稍微误解了如何使用数组。创建数组就像这样
GameEntry[] scoreArray = new GameEntry[4];
这个数组现在可以容纳 4
GameEntry
对象。是
// Declare
GameEntry[] scoreArray;
// Allocate
scoreArray = new GameEntry[4];
您可以使用它们的索引来设置和访问这些对象,就像这样
// Set the first object, at index 0
scoreArray[0] = new GameEntry(10);
// Set the second object, at index 1
scoreArray[1] = new GameEntry(100);
// Access the first object
System.out.println(scoreArray[0].scores);
// Access the second object
System.out.println(scoreArray[1].scores);
此外,您的 print 语句没有多大意义:
for (int i = 0; i < scoreArray.length; i++) {
System.out.println(Arrays.toString(scoreArray));
}
它在每次迭代中再次对整个数组进行字符串化。那么为什么要把它包含在一个循环中呢?您可能打算迭代数组并手动访问元素。 Arrays.toString
方法本身已经迭代了数组。这就像问 4
次相同的问题“完整的数组是什么样子的?”
解决方案
所以你的代码应该看起来像
// Declare and allocate the array
GameEntry[] scoreArray = new GameEntry[4];
// Set elements at indices 0-3
scoreArray[0] = new GameEntry(10);
scoreArray[1] = new GameEntry(100);
scoreArray[2] = new GameEntry(1000);
scoreArray[3] = new GameEntry(10000);
// Iterate the array
for (int i = 0; i < scoreArray.length; i++) {
// Access the element at index i
GameEntry currentObject = scoreArray[i];
// Print some info about the object
System.out.println("Current object is: " + currentObject);
System.out.println("It has a score of: " + currentObject.scores);
}
打印对象注意事项
如果你打印一个像这样的对象
// GameEntry@15db9742
System.out.println(currentObject);
它将调用currentObject.toString()
,这是每个对象都有的方法(因为它是每个类都隐式扩展的Object
类的一部分)。如果您不覆盖此方法,它将回退到 Object
类的默认实现,该类打印类名和一些标识当前 JVM 实例中的对象的代码。
这里是你如何覆盖它
class GameEntry {
// Other stuff
...
@Overwrite
public String toString() {
return "GameEntry[score=" + scores + "]";
}
}
现在语句将像这样打印
// GameEntry[score=10]
System.out.println(currentObject);
关于java - 创建类存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069352/