CCD
CCD

Reputation: 492

Element in array's index location

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!

Upvotes: 0

Views: 101

Answers (3)

Veronica Cornejo
Veronica Cornejo

Reputation: 488

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

Based on this quoted part of the question, please consider the following answer:

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

A more general solution:

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 >

Note: this code works both for Inventory being an array, a List, or in general a Collection.

Upvotes: 0

arynaq
arynaq

Reputation: 6870

You can do this with arrays, but it can be errorprone and so requires alot of defensive coding. In class Item: public int getID(){return this.id;}

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

If the element is not in the inventory an error will be thrown. It is better to use a list but if you insist on arrays.

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];
}

Upvotes: 0

nanofarad
nanofarad

Reputation: 41291

You might not be able to do so in this case, due to the scope of the array and the fact that the class is not aware of its surroundings.

use a list of objects, and use:

myList.indexOf(item)

to get an int index.

The Item class should also include an equals( method.

Upvotes: 3

Related Questions