Your code example runs in exactly the same way whether you use:
List<MyClass> data = new ArrayList<>();
…or you use:
ArrayList<MyClass> data = new ArrayList<>();
Referring to an object by its more general interface (or superclass) as seen in the first version does not change any behavior. In both examples above, you are manipulating an array-backed list, an ArrayList
object.
When choosing a particular implementation of List
, such as LinkedList
or ArrayList
, you must consider how the list will likely be used in your code. We have multiple implementations because various programs have various needs. For example, if you program is doing many arbitrary accesses by specific position within the list, use ArrayList
. If you are doing many edits to insert/delete various elements within the list, then use LinkedList
. Each kind of List
has its particular advantages.
The point of referring to the collection by its more general interface rather than the specific concrete class is that other code referring to that list will not break when you decide to change from one kind of list to another. If you come to realize that your code will be doing insertions/deletions in the middle of the list more often than arbitrary access by position, you can change this:
List<MyClass> data = new ArrayList<>();
…to this:
List<MyClass> data = new LinkedList<>();
…without breaking any other code referring to data
.
Of course this assumes the other code is satisfied by the methods available on the interface. If your code requires calls to the methods specific to the ArrayList
class, then you must refer to the list as a ArrayList
rather than as a List
.
The last paragraph of yours is unclear. Your mentions about "too many random accesses" and "too slow processing" are not explained. So edit your Question if your concerns have not been addressed.
By the way, be aware of the many useful utility methods in the Collections
class. To get random elements from List
, you could copy the list and then call Collections.shuffle
to move the elements into randomly-chosen positions.
List< String > names = List.of( "Alice" , "Bob" , "Carol" , "Duke" ) ;
List< String > namesRandom = new LinkedList<>( names ) ; // Copy the list into a second list to leave the original intact.
Collections.shuffle( namesRandom ) ; // Move around the element positions within this second list.
See this code run live on IdeOne.com.
names = [Alice, Bob, Carol, Duke]
namesRandom = [Bob, Carol, Alice, Duke]