0

Suppose I have a class. It is called Item.

public class Item {

public boolean usable = false;
protected boolean usage;    
public int id;
public String name;
public String type;
public int stacknum;
protected int tier;
public String rarity;
boolean equipable;
boolean equiped;
String altName;


public Item(int idIn, String nameIn, String typeIn) {

    usage = false;
    id = idIn;
    name = nameIn;
    type = typeIn;
    stacknum = 0;
    tier = 0;
    rarity = "Common";

}//end of constructor
}//end of class

Lets say I have an array called:

Inventory = new Item[5];

It contains these elements:

Item elementOne = new Item(1, "Element One", "Array Element");
Item elementTwo = new Item(2, "Element Two", "Array Element");

etc.

Inventory[0] = elementOne;
Inventory[1] = elementTwo;
Inventory[2] = elementThree;

and so forth. How would I go about writing a method to find out which element in array an Item(or anything in general) is I.e.

elementOne.findPlace

would return the int value of 0.

thanks!

4

3 回答 3

3

在这种情况下,您可能无法这样做,因为数组的范围以及类不知道其周围环境的事实。

使用对象列表,并使用:

myList.indexOf(item)

得到一个 int 索引。

Item 类还应该包含一个equals(方法。

于 2013-08-22T06:28:37.270 回答
0

我将如何编写一种方法来找出数组中的哪个元素 Item (或一般的任何东西

根据问题的引用部分,请考虑以下答案:

Item result= null ;
for(Item e: Inventory) {
    if( <whatever-your-search-condition-is> ) {
        result= e ;
        break;
    }
}
if( result != null )
    <found>
else
    <not found>

更通用的解决方案:

List<Item> result= new LinkedList<Item>() ;
for(Item e: Inventory) {
    if( <whatever-your-search-condition-is> )
        result.add( e );
}
if( result.size() > 0 )
    < result.size() found >
else
    < none found >

注意:此代码适用于 Inventory 作为数组、 aList或通常的 a Collection

于 2013-08-22T06:45:09.680 回答
0

你可以用数组来做到这一点,但它很容易出错,因此需要大量的防御性编码。课堂项目:public int getID(){return this.id;}

int index = Inventory[element.getID()-1];

如果该元素不在库存中,则会引发错误。最好使用列表,但如果您坚持使用数组。

public static int getIndexOfItem(Item item, Item[] inventory){
  if(inventory == null || item == null)
    return -1;
  if (item.getID()-1 > inventory.length)
    return -1;
  return inventory[item.getID()-1];
}
于 2013-08-22T06:37:22.103 回答