-5

For a project I want to check if a String is the same as a String attribute in one of my objects.

For example, I have 3 item object:

Item spotion = new Item("small potion", 5, 0, 0, 0, 0, 0);
Item mpotion = new Item("medium potion", 20, 0, 0, 0, 0, 0);
Item lpotion = new Item("large potion", 35, 0, 0, 0, 0, 0);

I would then want to check if

String s = spotion;

would equal any of the Item's name (first attribute);

Would there be any way to do this without creating an ArrayList of items to loop through but instead just see how many items there are and loop on when created?

  • You need a public field or getter in the `Item` class to get to that first attribute. – Thilo Jan 14 '19 at 12:06
  • 1
    `item.name.equals("some string")` – Lino Jan 14 '19 at 12:06
  • 1
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Lino Jan 14 '19 at 12:07
  • I already have a getter the problem is that I don't know how I would setup a loop for the Items without having to creating an ArrayList where it can loop through. – Jami Saueressig Jan 14 '19 at 12:08
  • You can use streams: `long count = Stream.of(spotion, mpotion, lpotion).filter(item -> item.name.equals(s)).count()` – Lino Jan 14 '19 at 12:11

1 Answers1

2

To loop through the objects you would have to put them into an array first, like this:

Item[] items = new Item[] {
    new Item("small potion", 5, 0, 0, 0, 0, 0),
    new Item("medium potion", 20, 0, 0, 0, 0, 0),
    new Item("large potion", 35, 0, 0, 0, 0, 0),
}

Then you'd be able to loop through the array using the plain old for loop:

for(int i = 0; i < items.length; i++){
    //your code here
}

Or the enhanced for loop:

for(Item item : items){
    //your code here
}

To compare the variable all you'd have to do is compare the appropriate variable using equals:

if(item.yourVariable.equals(string)){
    //your code here
}

You can't compare the String directly to your object unless you override its toString method. Instead, you'll have to compare the desired property.

Ayrton
  • 2,218
  • 1
  • 14
  • 25
  • Just as a side note: When instantiating and assigning arrays directly to a variable the `new Item[]` can be omitted, else a good answer +1 :) – Lino Jan 14 '19 at 12:14