-1

I have a String 2D-array named items in my app like this :

    String[][] items = {

            {"(kilogram)","1"},
            {"(gram)","1000"},
            {"(pound)","2.20462262"},
            {"(pound - troy)","2.6792288807"},
            {"(carat)","5000"},
            {"(ounce)","35.2739619"},
            {"(ounce - troy)","32.1507466"},

     }

and I want to have a String ArrayList that include first parameter of each item data, something like this :

ArrayList<String> data = new ArrayList<>();
data = {(kilogram),(gram),(pound),(pound - troy),(carat),(ounce),(ounce - troy)}

i used this code but unfortunately it didn't work

    ArrayList<String> data = new ArrayList<>();

    for (int i = 0; i <= items.length;) {
        data.add(items[i][0]);
        i++;
    }
dialex
  • 2,706
  • 8
  • 44
  • 74
Daniel Mohajer
  • 117
  • 2
  • 8
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OH GOD SPIDERS Dec 01 '21 at 11:32
  • 1
    change `i <= items.length` to `i < items.length` and you'll get your desired result – OH GOD SPIDERS Dec 01 '21 at 11:33

1 Answers1

1

You can also use streams to build this list:

List<String> data = Stream.of(items)
        .map(item -> item[0])
        .collect(Collectors.toList());

If you still want to use a for loop go with (use < instead of <=):

for (int i = 0; i < items.length; i++) {
    data.add(items[i][0]);
}
csalmhof
  • 1,820
  • 2
  • 15
  • 24