1

I am new to Java. I apologize if I ask a simple thing. I wrote the below code but it seems that it doesn't initialize properly. because when I print the size of list1 it show the size = 0!! However, it should be 4!

public static class MyClass{
        public List <Integer> list1

        // Class Constructor
        public MyClass(int n){          
            list1 = new ArrayList <Integer> (n);
            System.out.println("Size = " + list1.size() ); 
                    // prints Size = 0 !!!why???
        }

        public void init(int n){ 
            for(int cnt1 = 0; cnt1 < list1.size(); cnt1++){
            list1.set(cnt1 , cnt1);
            }
        }
        ...}



public static List<Integer> Func1(int n){
        MyClass = new myclass (n); 
        myclass.init(n);
        ... }


public static void main(String args[]){
        int n = 4;
        result = Func1 (n);
        ...}

Why the size of the list1 is 0? It should be 4, because I pass 4 to Func1, and then it creates MyClass object with size n. I would be thankful if someone can help me about this problem.

1
  • 1
    You misunderstand capacity and size. Commented Oct 21, 2013 at 19:02

2 Answers 2

2

Array lists in Java have both a size and a capacity.

  • Size tells you how many items are there in the list, while
  • Capacity tells you how many items the list can hold before it needs to resize.

When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size.

Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it.

Sign up to request clarification or add additional context in comments.

Comments

1

You have used the ArrayList constructor that determines its initial capacity, not its initial size. The list has a capacity of 4, but nothing has been added yet, so its size is still 0.

Quoting from the linked Javadocs:

Constructs an empty list with the specified initial capacity.

Also, don't use set to add to the list. That method replaces an element that is already there. You must add to the list first (or use the other overloaded add method).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.