Java 获取数组中项目的索引

Java 获取数组中项目的索引,java,inheritance,printing,while-loop,java.util.scanner,Java,Inheritance,Printing,While Loop,Java.util.scanner,如果我向数组列表中添加了两个项,并且这两个项具有相同的名称,那么当我要打印它们时,它们的索引将与我调用indexOf()方法时的索引相同,它将返回元素第一次出现的索引,获取这些项的索引的最佳方法是什么,我试图声明一个局部变量,并将计数器的值关联到它,在我刚才添加的print语句中,它确实起了作用,但我认为这应该是一种更好的方法 public class Example { public void checkIndex(int index) {

如果我向数组列表中添加了两个项,并且这两个项具有相同的名称,那么当我要打印它们时,它们的索引将与我调用indexOf()方法时的索引相同,它将返回元素第一次出现的索引,获取这些项的索引的最佳方法是什么,我试图声明一个局部变量,并将计数器的值关联到它,在我刚才添加的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 | |索引>=size)//更小
抛出新的IndexOutOfBoundsException
(“index=“+index+”size=“+size”);
}
公共对象get(int索引)
{
检查索引(索引);
返回元素[索引];
}
公共int索引(对象元素)
{
//在元素[]中搜索该元素
对于(int i=0;i
您可以通过以下方式设计类:

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

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

您可以通过以下方式设计类:

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

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

只要您不使用原语,ArrayList.indexOf就可以工作,如果您使用原语,您可以只使用类(即int和Integer)@TAAPSogeking,它要么不清楚,要么不准确。。。问题是关于IndexOf本身的实现,没有ArrayList。我很抱歉。我不确定我是否理解。你想让我们在你的代码中找到问题,还是仅仅提供重复命名问题的解决方案?@mohamedghassar你完成了吗?这个问题回答了吗?只要您不使用原语,ArrayList.indexOf就可以工作,如果您使用原语,您可以使用不清楚或不准确的类(即int和Integer)@TAAPSogeking。。。问题是关于IndexOf本身的实现,没有ArrayList。我很抱歉。我不确定我是否理解。你想让我们在你的代码中找到问题,还是仅仅提供重复命名问题的解决方案?@mohamedghassar你完成了吗?这个问题有答案吗?