Reputation: 7
I have got a 2d String array. How can I check a slice of it? For example row 3, up to 6th element there
I have tried
String arr[][] = new String[3][6]
arr[3][4] = "example"
if (Arrays.asList(arr).subList(3,6).contains("example"))
System.out.print("yes");
But this doesn't work. It works only for 1d array? Also, instead of using contains how can one check whether all elements are null in the slice array?
Upvotes: 0
Views: 5590
Reputation: 3475
You declare that String arr[][] = new String[3][6]
, it means simply 3 rows 6 columns structure.
Can assign value, in this case row,
arr[0][...] = <assigned-value>
//row 1arr[1][...] = <assigned-value>
//row 2arr[2][...] = <assigned-value>
//row 3But it will not work as you expected
arr[3][4] = "example"
//row 4, here throwing ArrayIndexOutOfBoundsException
Upvotes: 0
Reputation: 75585
First of all, arrays are zero-indexed in Java, so if you declare an array with first dimension 3
, the maximum index is 2
.
Second, if you want to look at the slices of the third row, you should specify the index 2
explicitly before converting to a list.
import java.util.*;
public class ArrayGame {
public static void main(String[] args) {
String arr[][] = new String[3][6];
arr[2][4] = "example";
if (Arrays.asList(arr[2]).subList(3,6).contains("example"))
System.out.println("yes");
}
}
Output:
yes
Upvotes: 2
Reputation: 720
The curent way to do it is just :
if (Arrays.asList(arr[3]).contains("example"))
System.out.print("yes");
Good luck!
Upvotes: 0
Reputation: 3691
Look in javadoc Arrays:
Arrays.copyOfRange(T[] original, int from, int to)
where
original is, for example, arr[3]
from is 0
to is 7
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange%28T[],%20int,%20int%29
Upvotes: 0