How to use ArrayList's get() method

后端 未结 5 2017
长发绾君心
长发绾君心 2021-01-04 13:27

I\'m new to java (& to OOP too) and I\'m trying to understand about the class ArrayList but I don\'t understand how to use the get(). I tried searching in net, but could

5条回答
  •  醉话见心
    2021-01-04 13:49

    To put it nice and simply, get(int index) returns the element at the specified index.

    So say we had an ArrayList of Strings:

    List names = new ArrayList();
    names.add("Arthur Dent");
    names.add("Marvin");
    names.add("Trillian");
    names.add("Ford Prefect");
    

    Which can be visualised as: Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

    Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

    So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

提交回复
热议问题