I am newly learning java.I am trying to understand the various data structures in util package.
/*create an ArrayList object*/
List<String> arrayList = new ArrayList<String>();
In the decleration of ArrayList class I have seen
public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
My question is if I use an object of type List<> to store the object returned by constructor of ArrayList<>
will it work.You may assume that I need to use only the methods specified in the List interface,such as add() or size().
I have tried this on my machine and it does not work.I found this in the java tutorial below
The complete example code that I tried is as below.
package arraylist;
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args)
{
/*create an ArrayList object*/
List<String> arrayList = new ArrayList<String>();
/*
Add elements to Arraylist using
boolean add(Object o) method. It returns true as a general behavior
of Collection.add method. The specified object is appended at the end
of the ArrayList.
*/
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
/*
Use get method of Java ArrayList class to display elements of ArrayList.
Object get(int index) returns and element at the specified index in
the ArrayList
*/
System.out.println("Getting elements of ArrayList");
System.out.println(arrayList.get(0));
System.out.println(arrayList.get(1));
System.out.println(arrayList.get(2));
}
}
I forgot to import List.that is why it did not work.However my next question is we use a variable of type List to store on object of type ArrayList.
Comparing the methods of List and ArrayList ArrayList has a method called trimToSize() that is not there in list.
In the above case will I be able to call that method?
If yes,what that generally means is that a base class pointer can be used to store a derived class object as the method list of derived class will always be a super-set of base class methods?
Is my above conclusion correct? It my sound stupid question but I am very new to java.