user3758223
user3758223

Reputation: 7

Get an array slice of 2d array

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

Answers (4)

Wundwin Born
Wundwin Born

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 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

Upvotes: 0

merlin2011
merlin2011

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

Yakir Yehuda
Yakir Yehuda

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

jhamon
jhamon

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

Related Questions