2013-10-30 130 views
1

如果我将两个项目添加到我的数组列表中,并且这两个项目具有相同的名称,那么当我要打印它们时,它们将具有与调用方法时相同的索引indexOf()它将返回元素的第一个出现的索引,获得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

ArrayList.indexOf将工作,只要你不使用原语,如果你是你可以只使用类(即int和整数) – TAAPSogeking

+0

@TAAPSogeking这要么不明确或不准确...问题是要问自己的问题实现IndexOf,没有ArrayList。 –

+0

对不起。我不确定我是否理解。您是否希望我们在您的代码中找到问题,或只是提供重复命名问题的解决方案? – TAAPSogeking

回答

1

你可以设计在某种程度上你的类的更好的方式来提供以下功能:

IndexOf(object obj) // giving index of first occurrence 

IndexOf(object obj, int startIndex) // giving index of first occurrence after the specified index