K
K
Koshkasobaka2020-03-22 21:48:31
Java
Koshkasobaka, 2020-03-22 21:48:31

Java. Why does the loop not take the size of the list?

Hello. I just started working with lists and I can not understand one moment. I create a list of strings and immediately indicate in parentheses the size of the list (10). Next, I want to fill in the list, and here, if you specify i < list.size () in the cycle header, then the console displays: Process finished with exit code 0. And if I write i < 10, then everything is OK. Then, when I display the list on the screen, the program calmly accepts i < list.size (), but here it is clear that the size of the list is returned. But why doesn't he see it in the first loop?

ArrayList<String> list = new ArrayList<>(10);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          for (int i = 0; i < 10; i++) {                     // вот тут хочу  list.size()
            System.out.println("строка: ");
            String s = reader.readLine();
            list.add(0, s);
        }

       for (int i = 0; i < list.size(); i++)
           System.out.println(list.get(i));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-03-22
@Koshkasobaka

Because the size method returns the number of elements in the list, and the number passed to the constructor indicates the initial capacity of the list. Figuratively speaking, if you took a three-liter jar, this does not mean that it contains three liters of water.

S
sergey, 2020-03-22
kuzmin @sergueik

Koshkasobaka to initialize a fixed length list is often used
something like

List<String> names = new ArrayList<>(
        Arrays.asList(new String[] { "ильф", "петров" }));

it’s possible for a friend, of course, but it’s quite convenient for mine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question