如何返回Object数组的索引?

时间:2013-02-27 11:08:18

标签: java

我在尝试返回索引时遇到错误(必须返回一个int),我看不出我做错了什么。如何将Object数组索引与int进行比较,并返回索引号?

//x starts at 10000 because the left most number is assumed to be at least a 1.
/**
 * Search for a book id within the Book object array
 * @param Book - Array of objects with book id, title, isbn, author, and category
 * @param numOfBooks - how many books are in the library
 * @param myBookID - The key to search for
 * @return the index of the array where the key matches
 */
public static int bookSearch (Object[] Book, int numOfBooks, int myBookID) {
    for (int x = 10000; x <= numOfBooks; x ++)
        if (Book[x].equals(myBookID))
            return x;
}

8 个答案:

答案 0 :(得分:4)

你需要在最后添加一个额外的回报,因为你的if条件永远不会匹配。

public static int bookSearch (Object[] Book, int numOfBooks, int myBookID) {
    for (int x = 10000; x <= numOfBooks; x ++) {
        if (Book[x].equals(myBookID))
            return x;
    }

    return -1;
}

在旁注中,您可能想要检查数组的边界,而不是假设您最多有10000个项目。您还可以利用所有数组都具有length属性的事实,以避免传入您的一个参数:

public static int bookSearch (Object[] books, int myBookID) {
    if(books.length < 100000) return -1;

    for (int x = 10000; x <= books.length; x++) {
        if (Book[x].equals(myBookID))
            return x;
    }

    return -1;
}

答案 1 :(得分:2)

你可能正在寻找类似的东西:

public static int bookSearch (Book[] books, int myBookID) {
    for (int x = 0; x < books.length; x++)
        if (books[x].getId() == myBookID)
            return x;
    return -1; // not found
}

答案 2 :(得分:2)

仅适用于javascript,

您可以轻松找到索引编号。来自对象数组列表中的对象

中的任何属性
function _findIndexByKeyValue(arraytosearch, key, valuetosearch) {
    for (var i = 0; i < arraytosearch.length; i++) {
        if (arraytosearch[i][key] == valuetosearch) {
            return i;
        }
    }
    return -1;
}

应用上述方法

var index = _findIndexByKeyValue(objectArrayList, "id", objectArrayList.id); // pass by value
if (index > -1) {
    // your code 
}

数组列表

var objectArrayList = [{
    property1: 10,
    property2: 11,
    timestamp: "date-001",
    id: 1
}, {
    property1: 10,
    property2: 11,
    timestamp: "date-002",
    id: 2
}, {
    property1: 10,
    property2: 14,
    timestamp: "date-002",
    id: 3
}, {
    property1: 17,
    property2: 11,
    timestamp: "date-003",
    id: 4
}];

答案 3 :(得分:0)

循环外应该有一个return语句,这样即使退出循环而不满足条件,函数也会返回一个int。

答案 4 :(得分:0)

如果equals从不匹配,则需要在循环外返回一个值。 另一种解决方案是在未找到时抛出异常。

你不能找到一个函数的结尾,它的返回类型不是void,而没有实际返回一个值(或抛出异常)。

答案 5 :(得分:0)

这是因为编译器看得比你更远,它还会考虑你的书不在数组中的情况。您返回什么然后

答案 6 :(得分:0)

如果equals永远不匹配,你必须在循环下添加第二个返回。

答案 7 :(得分:0)

问题是,如果在if内部计算的表达式始终为false,则可能永远不会达到if语句内部的返回。

只需在for循环外添加“默认”返回!