Java—如何获取数组中给定元素的索引

Java—如何获取数组中给定元素的索引,java,arrays,indexing,Java,Arrays,Indexing,我有一系列联系人,如下所示: public class Application { private Scanner input; private Contact[] contacts; private int ArrayNum; public Application() { input = new Scanner(System.in); contacts = new Contact[5]; ArrayNum = 0; } 我想做的是在联系人列表中输入一个人的名字,

我有一系列联系人,如下所示:

public class Application {

private Scanner input;
private Contact[] contacts;
private int ArrayNum;

public Application() {
    input = new Scanner(System.in);
    contacts = new Contact[5];
    ArrayNum = 0;

}
我想做的是在联系人列表中输入一个人的名字,如果在他们的列表中找到他们,返回他们的索引,如下所示:

System.out.println("Who do you want to remove?");

            String name = input.nextLine();

            for(Contact c: contacts){
                if(c.getName().equals(name)){

                    //Get the index here
                }
            }
我试着研究这一点,但没有答案或指南似乎是非常明确的,所以我希望有人能解释这一点给我

感谢您查找(int index=0;indexfor(int index = 0; index < contacts.length; index++) { if(contacts[index].getName().equals(name)) { // use the index here } } if(contacts[index].getName().equals(name)){ //使用这里的索引 } }
我认为这个代码片段不需要任何进一步的解释。

您可以使用计数器

System.out.println(“您想删除谁?”)

String name=input.nextLine();
int remove_index=-1;

for(int i=0;i使用使用计数器的for循环

for(int i = 0; i < contacts.length, i++) {
    if(contacts[i].getName().equals(name)) {
        // do something with the index, i
    }
}
for(int i=0;i
另一种可能有用的替代方法是使用而不是c样式的数组(
Contact[]
)。此类可能会增加更多的处理复杂性,但它包含许多有用的额外方法,包括
int indexOf(object)
其中
是您在声明中指定的类型(即
联系人
用于
ArrayList联系人
)。

坏主意!如果您有一个数组,您不能认真地这么做。当然,您可以将索引设置为null,但随后必须搜索null条目以引用数组中的新联系人。 注意:您在编写时有一个迭代器

for(Contact c: contacts){...
因此,一个选项是按索引进行迭代,但这是一个坏选项。最好将数组设置为一个集合。然后您可以编写:

for (Iterator<Contact> iter = mySet.iterator();iter.hasNext();) {
    final Contact next = iter.next();
    if(next.getName() == "NAME") {
         iter.remove();
         break;
    }
for(Iterator iter=mySet.Iterator();iter.hasNext();){ 最终接触下一步=iter.next(); if(next.getName()=“NAME”){ iter.remove(); 打破 }

始终使用迭代器.remove()!否则您将比您希望的更早获得异常:D

使用使用计数器的for循环。您知道除了增强for循环
for(Element el:elements)
之外,还有一个简单的for循环
for(int i=0;i使用
列表
,该列表具有
indexOf()
。我看不出OP在哪里说过要从数组中删除项目……OP想要获取项目的索引。因此,这并不能回答问题中的任何问题。
for (Iterator<Contact> iter = mySet.iterator();iter.hasNext();) {
    final Contact next = iter.next();
    if(next.getName() == "NAME") {
         iter.remove();
         break;
    }