1

I was hoping there is some way in java do to as the title says. For example:

int Num1 = 5;
int Num2 = 9;
char Char1 = 'a';
char Char2 = 'g';
char[] CharArray = {'1','2','3','4','5','6','7','8'
                    '9','a','b','c','d','e','f'}

I would like it to return true for Num1, Num2, and Char1, while Char2 should return false.

I know in MATLAB it's quite easy, you can simply just do:

ismember([Num1 Num2 Char1 Char2], CharArray)

This will return 1,1,1,0

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Josh Beckwith
  • 1,432
  • 3
  • 20
  • 38

3 Answers3

2

Does it have to be an array? If not, how about:

String allowedCharacters = "123456789abcdef";

allowedCharacters.contains("a"); // true
allowedCharacters.contains("g"); // false
allowedCharacters.contains(String.valueOf(5)); // true
allowedCharacters.contains(String.valueOf(-1)); // false
jmrah
  • 5,715
  • 3
  • 30
  • 37
0

As far as I know Java doesn't provide a method comparable to the MATLAB method you mention, but it shouldn't be too hard to implement - the Arrays.binarySearch method will be useful here.

If you don't mind having your charArray sorted along the way, you'd do something like

public boolean[] members(char[] needles, char[] haystack) {
  Arrays.sort(haystack);  // better to do this outside this method...
  boolean [] results = boolean[needles.length];
  for (int i = 0; i < needles.length; i ++) {
    results[i] = Arrays.binarySearch(haystack, needles[i]) >= 0;
  }
  return results;
}

(note: this code is not tested, and is just an illustration)

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

Did you try with something like this?

public static boolean useList(String[] arr, String targetValue) { 
    return Arrays.asList(arr).contains(targetValue);
 }
dccdany
  • 826
  • 7
  • 17