Adding a value to the list to initialize the size of the list

I have the code below:

Hashtable<Integer, List<Model>> map = new Hashtable<Integer, List<Model>>();
    for (int i = 0; i < arraylistAssignment.size(); i++) {
        List<Model> temp = null;
        for (int j = 0; j < arraylistModel.size(); j++) {
            if (arraylistAssignment.get(i).getId() == arraylistModel.get(j)
                    .getId()) {
                if (temp == null)
                    temp = new ArrayList<Model>();// DEBUG POINT 1

                temp.add(arraylistModel.get(j)); 

            }// DEBUG POINT 2 AFTER ADD FUNCTION ABOVE

        }

        map.put(arraylistAssignment.get(i).getId(), temp);

    }

In the above code, at debug point 1, when I integrated the temporary variable in hv, the size of the object is 0 like showm below:

enter image description here

but as soon as I add ie temp.add, the size is 1, but the creation of the objects is 12, of which 11 values โ€‹โ€‹are zero, as shown below ... I could not understand the reason for the zero values โ€‹โ€‹here, maybe someone from plz exaplin. ..mi initilzing wrong?

enter image description here

enter image description here

+4
source share
4 answers

An ArrayList , , . " ". "", , , .

+2

null , ArrayList . , , . , , , , , , -, ArrayList , . , , size.

, , . ArrayList - size, , 1, .

+1

ArrayList - Collections, I.e. . , 10. , 11- .

, , , , . .

, , . STARTS 0 10, 11 , 12-, api .

ArrayList:

+1

Java Dokumentation: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Each instance of ArrayList has a capacity. Capacity is the size of the array used to store items in a list. It is always no less than the size of the list. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not indicated beyond the fact that adding an item has a constant amortized cost of time.

In your case, the default capacity is 12, although it should be 10.

0
source

Source: https://habr.com/ru/post/1541007/


All Articles