Retrieve list in java

Java List Methods Tutorial – Util List API Example

Yiğit Kemal Erinç

Yiğit Kemal Erinç

Java List Methods Tutorial – Util List API Example

Lists are commonly used data structures in every programming language.

In this tutorial we are going to investigate Java’s List API. We’ll start off with basic operations, and then we will get into more advanced stuff (like a comparison of different list types, such as ArrayList and LinkedList).

I will also give you some guidelines to help you choose the list implementation that is best for your situation.

Although basic Java knowledge is enough for following the tutorial, the last section requires basic data structures (Array, LinkedList) and Big-O knowledge. If you are not familiar with those, feel free to skip that section.

Definition of Lists

Lists are ordered collections of objects. They are similar to sequences in math in that sense. They’re unlike sets, however, which do not have a certain order.

A couple of things to keep in mind: lists are allowed to have duplicates and null elements. They are reference or object types, and like all objects in Java, they’re stored in the heap.

A list in Java is an interface and there are many list types that implement this interface.

ListHierarchy

I will use ArrayList in the first few examples, because it is the most commonly used type of list.

ArrayList is basically a resizable array. Almost always, you want to use ArrayList over regular arrays since they provide many useful methods.

An array’s only advantage used to be their fixed size (by not allocating more space than you need). But lists also support fixed sizes now.

How to Create a List in Java

Enough chatting, let’s start by creating our list.

import java.util.ArrayList; import java.util.List; public class CreateArrayList < public static void main(String[] args) < ArrayListlist0 = new ArrayList<>(); // Makes use of polymorphism List list = new ArrayList(); // Local variable with "var" keyword, Java 10 var list2 = new ArrayList(); > >

In the angle brackets (<>) we specify the type of objects we are going to store.

Keep in mind that the type in brackets must be an object type and not a primitive type. Therefore we have to use object wrappers, Integer class instead of int, Double instead of double, and so on.

There are many ways to create an ArrayList, but I presented three common ways in the snippet above.

The first way is by creating the object from the concrete ArrayList class by specifying ArrayList on the left hand side of the assignment.

The second code snippet makes use of polymorphism by using list on the left hand side. This makes the assignment loosely coupled with the ArrayList class and allows us to assign other types of lists and switch to a different List implementation easily.

Читайте также:  Php convert number to numbers

The third way is the Java 10 way of creating local variables by making use of the var keyword. The compiler interprets the type of variable by checking the right hand side.

We can see that all assignments result in the same type:

System.out.println(list0.getClass()); System.out.println(list.getClass()); System.out.println(list2.getClass());
class java.util.ArrayList class java.util.ArrayList class java.util.ArrayList 

We can also specify the initial capacity of the list.

List list = new ArrayList<>(20);

This is useful because whenever the list gets full and you try to add another element, the current list gets copied to a new list with double the capacity of the previous list. This all happens behind the scenes.

This operation makes our complexity O(n), though, so we want to avoid it. The default capacity is 10, so if you know that you will store more elements, you should specify the initial capacity.

How to Add and Update List Elements in Java

To add elements to the list we can use the add method. We can also specify the index of the new element, but be cautious when doing that since it can result in an IndexOutOfBoundsException.

import java.util.ArrayList; public class AddElement < public static void main(String[] args) < ArrayListlist = new ArrayList<>(); list.add("hello"); list.add(1, "world"); System.out.println(list); > >

We can use the set method to update an element.

list.set(1, "from the otherside"); System.out.println(list);
[hello, world] [hello, from the otherside]

How to Retrieve and Delete List Elements in Java

To retrieve an element from the list, you can use the get method and provide the index of the element you want to get.

import java.util.ArrayList; import java.util.List; public class GetElement < public static void main(String[] args) < List list = new ArrayList(); list.add("hello"); list.add("freeCodeCamp"); System.out.println(list.get(1)); > >

The complexity of this operation on ArrayList is O(1) since it uses a regular random access array in the background.

To remove an element from the ArrayList, the remove method is used.

This removes the element at index 0, which is «hello» in this example.

We can also call the remove method with an element to find and remove it. Keep in mind that it only removes the first occurrence of the element if it is present.

public static void main(String[] args)

To remove all occurrences, we can use the removeAll method in the same way.

These methods are inside the List interface, so every List implementations has them (whether it is ArrayList, LinkedList or Vector).

How to Get the Length of a List in Java

To get the length of a list, or the number of elements, we can use the size() method.

import java.util.ArrayList; import java.util.List; public class GetSize < public static void main(String[] args) < List list = new ArrayList(); list.add("Welcome"); list.add("to my post"); System.out.println(list.size()); >> 

Two-Dimensional Lists in Java

It is possible to create two-dimensional lists, similar to 2D arrays.

ArrayList> listOfLists = new ArrayList<>();

We use this syntax to create a list of lists, and each inner list stores integers. But we have not initialized the inner lists yet. We need to create and put them on this list ourselves:

int numberOfLists = 3; for (int i = 0; i < numberOfLists; i++) < listOfLists.add(new ArrayList<>()); >

I am initializing my inner lists, and I am adding 3 lists in this case. I can also add lists later if I need to.

Читайте также:  Php json encode library

Now we can add elements to our inner lists. To add an element, we need to get the reference to the inner list first.

For example, let’s say we want to add an element to the first list. We need to get the first list, then add to it.

image-72

Java ArrayList vs Vector

Vector is very similar to ArrayList. If you are coming from a C++ background, you might be tempted to use a Vector, but its use case is a bit different than C++.

Vector’s methods have the synchronized keyword, so Vector guarantees thread safety whereas ArrayList does not.

You might prefer Vector over ArrayList in multithreaded programming or you can use ArrayList and handle the synchronization yourself.

In a single-threaded program, it is better to stick with ArrayList because thread-safety comes with a performance cost.

Conclusion

In this post, I have tried to provide an overview of Java’s List API. We have learned to use basic methods, and we’ve also looked at some more advanced tricks to make our lives easier.

We also made a comparison of ArrayList, LinkedList and Vector which is a commonly asked topic in interviews.

Thank you for taking the time to read the whole article and I hope it was helpful.

You can access the whole code from this repository.

If you are interested in reading more articles like this, you can subscribe to my blog’s mailing list to get notified when I publish a new article.

Источник

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

Читайте также:  Html button javascript value

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Оцените статью