1

Let's say I got this array:

String[][]array = new String[5][5];

array[2][2] = desperate;

Would it be possible to find whether

String s = "desperate"; - equals any array element without using a for loop, and without having to manually enter the row column combination of the array assigned the value "desperate"?

Sing Sandibar
  • 714
  • 4
  • 15
  • 26

4 Answers4

3

while loop instead of for loop

int i = 0;
int j = 0;  
while (i < n)  
{  
   while (j < m)  
   {  
      if (array[i][j].equals("..."))
      {  
         /// 
      }  
      j++;
   }   
   i++;    
}  
Ilya
  • 29,135
  • 19
  • 110
  • 158
  • I don't think the style of loop is really the key to the question, and generally most people prefer for loops http://stackoverflow.com/q/3875114/106261 – NimChimpsky Sep 28 '12 at 13:26
2

Use enhanced-for loop: -

String [][] array = new String[2][2];
array[1][1] = "desperate";
array[0][1] = "despee";
array[1][0] = "despete";
array[0][0] = "dete";

for (String[] innerArr: array) {
    for (String value: innerArr) {
         if (value.equals("desperate")) {
             System.out.println(value + " == desperate");
         }
    }
}

Output: - desperate == desperate

A better way that I would suggest is to use ArrayList<String> to store your items.. Then you can just call contains() method to check whether the list contains that element..

List<String> listString = new ArrayList<String>(); 
listString.add("desperate");
listString.add("despe");

if (listString.contains("desperate")) {
     System.out.println("True");
}

Output: - True

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • In the enhanced for loop does (String[] innerArr: array) only search the row arrays? – Sing Sandibar Sep 28 '12 at 13:39
  • Exactly.. Outer loop fetches you each row.. which is itself an array.. Now taking the variable(innerArr) from outer loop, we iterate over it to get each element.. – Rohit Jain Sep 28 '12 at 13:41
1

Assuming that you can't (for any reasons) change your array to another collection type:

String[][]array = new String[5][5];
array[2][2] = "desperate"; 


public boolean contains(String str){
  return new HashSet<String>((List<String>)Arrays.asList(array)).contains(str);
}

Better than transforming it to a List since HashSet's contains() method is O(1) and the one from List is O(n).

Mik378
  • 21,881
  • 15
  • 82
  • 180
0

The only way to avoid using a loop (and it not clear why you would want to) is to use a Map which you pre-build with all the strings and indexes.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130