0

I understand the the or operator is only for boolean expressions. So I was wondering if there is a good way to go about doing the code below without using the or operator?

if(hh.getName() != "apple" || "Health Potion" || "roatisary chicken" || "backpack")
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
QuestionHaver99
  • 104
  • 1
  • 6
  • Need a bit more context. Are all of these Strings relative? – Jason Mar 23 '20 at 13:31
  • 1
    `if (!Set.of("apple", "Health Potion" /* etc */).contains(hh.getName()))`. – Andy Turner Mar 23 '20 at 13:33
  • @Jason what does "relative" mean in relation to Strings? – Andy Turner Mar 23 '20 at 13:35
  • all Strings are in the constructor of subclasses of the same superclass called item that i use as an identifier as to which instance of the class is being used and to print out to the user which item is being used. But now i'm wondering if it would have been better to use instanceof in this scenario instead – QuestionHaver99 Mar 23 '20 at 13:35
  • @AndyTurner relative means in relation-to. The question is simply are all of these Strings related-to each other. – Jason Mar 23 '20 at 13:38
  • @AndyTurner cannot find Symble variable Set, do i need to import stuff? – QuestionHaver99 Mar 23 '20 at 13:38
  • @QuestionHaver99 Check below for an answer I provided. – Jason Mar 23 '20 at 13:38
  • @QuestionHaver99 I believe Set#of is only available in JDK9+ so you will need to update your JDK or use a third-party API like guava for ImmutableSet. – Jason Mar 23 '20 at 13:39
  • @Jason I still don't understand what you mean. Why does it matter if the strings are related to each other, beyond the fact they are all instances of String? – Andy Turner Mar 23 '20 at 18:28
  • @AndyTurner I.e like Wednesday and Tuesday are both days of the week, they are related to eschother. In Java we have the DayOfWeek enum to represent this easily. I was asking because we might be able to create an Enum to replace and represent these Strings. – Jason Mar 23 '20 at 18:40

1 Answers1

0

One possible solution if these are all related in some way is to store them in a Set of String objects. It is worth noting that this solution depends on each String being case sensitive.

Set<String> values = new HashSet<>(Arrays.asList("apple", "Health Poition", "roatisary chicken", "backpack"));

Then, check if set contains the String hh.getName()

if (values.contains(hh.getName()) {

}

A better solution A potentially even better solution would be to use an enumeration instead of a bunch of Strings.

enum Item {
   APPLE,
   HEALTH_POTION,
   ROATISARY_CHICKEN,
   BACKPACK
}
Set<Item> items = ImmutableMap.copyOf(EnumSet.allOf(Item.class));
Item myItem = ...;

if (items.contains(myItem)) {

}
Jason
  • 5,154
  • 2
  • 12
  • 22