如果我将两个项添加到我的数组列表中,并且这些两个项具有相同的名称,当我想要打印它们时它们将具有与我调用方法indexOf()时相同的索引它将返回第一个索引发生theElement,获取Items的索引的最佳方法是什么,我试图声明一个局部变量并为它计算计数器的值,并在我刚刚添加的print语句中 - 它确实有效但是我认为这应该是一种更好的方式
public class Example
{
public void checkIndex(int index)
{
if (index < 0 || index >= size) // smaller
throw new IndexOutOfBoundsException
("index = " + index + " size = " + size);
}
public Object get(int index)
{
checkIndex(index);
return element[index];
}
public int indexOf(Object theElement)
{
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}
}
public class Array extends Example
{
protected void printList()
{
int counter = 0;
if(super.size() == 0)
{
System.out.println("List is Empty.");
}
else
{
System.out.println("\nShowing List: ");
while(counter < super.size())
{
String s = (counter+1) + "\t" + super.get(counter).toString();
System.out.println(s + " the index is: " + super.indexOf(super.get(counter)));
}
}
System.out.println(); // this is to sprate the the options from the result.
}
}
答案 0 :(得分:1)
您可以通过提供以下内容的方式设计课程:
IndexOf(object obj) // giving index of first occurrence
IndexOf(object obj, int startIndex) // giving index of first occurrence after the specified index