【问题标题】:Element in array's index location数组索引位置中的元素
【发布时间】:2013-08-22 06:26:11
【问题描述】:

假设我有一堂课。它被称为项目。

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

假设我有一个名为:

Inventory = new Item[5];

它包含这些元素

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

等等

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

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

elementOne.findPlace

将返回 0 的 int 值。

谢谢!

【问题讨论】:

  • 为什么不覆盖 equals(Object o) 并将 List<T>contains(T item)indexOf(T item) 一起使用?
  • 我不完全明白你的意思。你能解释一下吗?
  • List<T> 中有一些有用的方法可以做你想做的事情(即indexOf(I item))。如果您在您的类Item 中实现equals(Object o) 方法,则可以使用它。我可以理解吗?
  • 是的,这样更有意义,谢谢

标签: java arrays indexing


【解决方案1】:

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

使用对象列表,并使用:

myList.indexOf(item)

获取一个 int 索引。

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

【讨论】:

  • +1。类似的事情也可以用数组来完成。但关键是你需要通过容器,因为元素本身“不知道它的周围环境”。
  • 需要提供Item.equals()方法
  • 对不起,我不完全理解您所说的“通过容器”是什么意思。另外,您能否提供一个 Item.equals() 方法的示例?
【解决方案2】:

您可以使用数组来做到这一点,但它很容易出错,因此需要大量的防御性编码。课堂内物品: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];
}

【讨论】:

    【解决方案3】:

    我将如何编写一种方法来找出数组中的哪个元素是一个项目(或任何一般的)是

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

    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、List 或一般的 Collection

    【讨论】:

    • 谢谢,我会考虑使用列表,因为这对我来说是一个新概念,似乎是一个流行的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2012-09-06
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多