格式:get(索引):对象。
public class MyArrayList {
public String[] arrays = {};
public MyArrayList() {
arrays = new String[10];
}
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
}
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
使用此代码,它会打印出:
测试构造函数、add(object) 和 size() 动物园现在有 10 只动物: 0 1 2 3 4 5 6 7 8 9
显然我的 get 方法代码是非常错误的,但它不应该打印出数字,而是应该打印出“Ant”,“Bison,”Camel”等。
感谢所有对代码的帮助,因为我是一个非常新的程序员。谢谢。
最佳答案
修复您的 Get 方法
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
好吧,让我们看看这个,好吗?用户可以提供一些值..
i < 0
0 < i < size of array <-- The only valid one.
i > size of array
所以首先你需要检查一下!
if(i > 0 && i < arrays.length) {
// This is a valid index!
}
好的,所以您知道这是一个有效的索引。第二步是检索值..
return arrays[i];
最后,需要设置返回类型。目前它是int
。在本例中它需要是String
..
public String get(int i)
就这么简单!当您调用 printZoo()
时,您将看到这些值,而不是它们的索引。
到您的对象
您可以拥有一个 Object
类型的数组,而无需导入任何类。这会将 String[]
类型的 arrays
更改为..
Object[] arrays;
关于java - 返回位置索引处的元素。 (无数组列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28439819/