0

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?

10
  • elaborate please, it is unclear what you are asking Commented Jun 27, 2014 at 22:38
  • well, I want to only get the slice of the 2d array arr[3][6] and check whether it contains "example" without looping through the whole array Commented Jun 27, 2014 at 22:41
  • you can just get the value stored at array[3][6], what you mean bu slicing further ? Commented Jun 27, 2014 at 22:43
  • @user3758223, It sounds like you are trying to get the entire row from arr[3]? Commented Jun 27, 2014 at 22:43
  • What do you consider a slice of a multidimensional array? Commented Jun 27, 2014 at 22:43

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

But that would copy the whole array and take up memory which is bad since I will have to do these checks in specific slices of the array many times.
0

The curent way to do it is just :

if (Arrays.asList(arr[3]).contains("example"))
        System.out.print("yes");

Good luck!

Comments

0

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 1
  • arr[1][...] = <assigned-value> //row 2
  • arr[2][...] = <assigned-value> //row 3

But it will not work as you expected

  • arr[3][4] = "example" //row 4, here throwing ArrayIndexOutOfBoundsException

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.