Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extend ArrayList in Java?

Is it possible to make a child class that extends ArrayList? If so, how?

like image 646
nambvarun Avatar asked Jan 24 '11 06:01

nambvarun


People also ask

Can an ArrayList be expanded?

The ArrayList size increases dynamically because whenever the ArrayList class requires to resize then it will create a new array of bigger size and copies all the elements from the old array to the new array. And now it is using the new array's reference for its internal usage.

How do you expand an ArrayList in Java?

However, ensureCapacity() method of java. util. ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Parameters: This method takes the desired minimum capacity as a parameter.

Can you change the length of an ArrayList?

The size of an ArrayList cannot be changed after the ArrayList is initialized. Immediately looking at the question, I would think the answer would be false. If you initialize an ArrayList, you can continue adding unlimited elements to it and the ArrayList will automatically resize.

What is the maximum length of ArrayList in Java?

The theoretical limit for ArrayList capacity is Integer. MAX_VALUE, a.k.a. 2^31 - 1, a.k.a. 2,147,483,647.


2 Answers

Yes you can.

public class MyArrayList<E> extends ArrayList<E> { } 

However, I'm not sure why you would want to do this.

like image 124
helloworld922 Avatar answered Oct 09 '22 01:10

helloworld922


You can extend any class that is not final in Java. Having said that, you should avoid inheritance if there is no true is-a relationship. Consider composition for reuse. Read about Liskov substitution principle

like image 31
Aravind Yarram Avatar answered Oct 09 '22 02:10

Aravind Yarram