Consider the following code segment: ArrayList bulbs = new ArrayList(); bulbs.add(new Light()); bulbs.remove(0); bulbs.add(new Light()); Light b = new Light(); bulbs.add(1, b); bulbs.add(new Light()); bulbs.remove(0); bulbs.add(new Light()); bulbs.remove(2); bulbs.add(new Light()); bulbs.add(1, new Light()); After running the code, what is the size of bulbs?

Respuesta :

To answer this, lets run through the code:

ArrayList bulbs = new ArrayList(); //create a new empty list

bulbs.add(new Light()); //size of bulbs  = 1

bulbs.remove(0); //remove item at index 0. size of bulbs = 0

bulbs.add(new Light()); // size of bulbs = 1

Light b = new Light();
bulbs.add(1, b); // size of bulbs = 2

bulbs.add(new Light()); //size of bulbs = 3

bulbs.remove(0); //remove bulb at index 0. Size of bulbs = 2

bulbs.add(new Light()); size of bulbs = 3

bulbs.remove(2); //remove bulb at index 2. size of bulbs = 2

bulbs.add(new Light()); //size of bulbs = 3

bulbs.add(1, new Light()); //inserted at position 1. size of bulbs = 4

The final answer. Size of bulbs = 4.

Answer:

4

Explanation:

ArrayList bulbs = new ArrayList();

bulbs.add(new Light()); // bulbs array length equal to 1

bulbs.remove(0); // bulbs array length equal to 0

bulbs.add(new Light()); // bulbs array length equal to 1

Light b = new Light();

bulbs.add(1, b); // bulbs array length equal to 2

bulbs.add(new Light()); // bulbs array length equal to 3

bulbs.remove(0); // bulbs array length equal to 2

bulbs.add(new Light()); // bulbs array length equal to 3

bulbs.remove(2); // bulbs array length equal to 2

bulbs.add(new Light()); // bulbs array length equal to 3

bulbs.add(1, new Light()); // bulbs array length equal to 4

ACCESS MORE