Announcing Bito’s free open-source sponsorship program. Apply now

Get high quality AI code reviews

Java List 用法: Java Explained

Table of Contents

Java is an object-oriented programming language which has been around for a long time and is still widely used today. One of the things that makes it popular is its lists, a powerful and versatile data structure that is essential to many programming tasks. In this article, we will look at how to create, use, and manipulate Java lists.

What is a Java List?

A Java list, also referred to as an ArrayList or Vector, is a type of data structure that allows you to store and manage a collection of objects. A list contains elements of any data type, including primitives such as int, double, boolean, and others, or complex types such as objects and even other lists. Unlike an array, a list can dynamically grow and shrink as elements are added and removed. This makes it ideal for storing and manipulating large collections of objects. It also provides many handy methods for manipulating the list in various ways.

For example, the list can be sorted, searched, filtered, and modified in a variety of ways. Additionally, the list can be used to store objects of different types, allowing for a more flexible and powerful data structure. Finally, the list can be used to store objects in a specific order, allowing for easy retrieval of objects in the order they were added.

How to Create a Java List

Creating a Java list is fairly easy and can be done in two steps. First, you need to import the List class into your program. To do this, add the following line of code at the top of your program:

import java.util.List;

Next, you need to declare the list. You can do this using either an array syntax:

List<Type> listName = new ArrayList<Type>();

or a type declaration syntax:

List<Type> listName = new List<Type>();

In both of these examples, Type is the type of object that your list holds, for example, integer, double, or string. You can replace Type with the specific type you want to store in the list.

Once you have declared your list, you can add elements to it using the add() method. For example, if you have a list of integers, you can add a new integer to the list using the following code:

listName.add(newInteger);

Adding Items to a Java List

Once you have created your list, you can start adding items to it. This can be done with the add() method, which takes one argument – the item you want to add to the list. Here’s an example:

listName.add(item);

The add() method is also overloaded, which means you can use it to add multiple items at once. You simply need to pass in the array or collection of items you want to add:

listName.addAll(arrayOfItems);

You can also add items to a specific index in the list using the add(int index, E element) method. This method takes two arguments – the index of the list where you want to add the item, and the item itself. Here’s an example:

listName.add(2, item);

Accessing List Values

Once you have added items to your list, you can access them using the get() method. This method takes one argument – the index of the item you want to access – and returns the item at that index. For example:

item = listName.get(index);

It is important to note that the index of the first item in a list is 0, not 1. This means that if you want to access the first item in a list, you would use the index 0. Additionally, if you try to access an item at an index that does not exist, the get() method will return a null value.

Removing Items from a Java List

If you need to remove an item from a Java list, you can do so with the remove() method. This method takes one argument – the index of the item you want to remove – and removes it from the list. Here’s an example:

listName.remove(index); 

It’s important to note that the remove() method will shift all the elements after the removed item to the left, so that the list remains in order. Additionally, the remove() method will return the item that was removed, so you can store it in a variable if needed.

Iterating Through a Java List

Iteration is the process of looping through each element in a collection. This can be done in Java with the for-each loop. Here’s an example:

for (Type item : listName) { 		 	 	 	 	 	     	 	 	 	         // Your code goes here 	 	 	 	 	 } 

In this code, Type is the type of object stored in the list, and item is the name of the variable used to store each item in turn.

The for-each loop is a convenient way to iterate through a list, as it eliminates the need to manually keep track of the index of the current item. This makes the code more readable and easier to maintain.

Sorting a Java List

Java lists can be sorted using the sort() method. This method takes a Comparator object as an argument, allowing you to customize how your list is sorted. Here’s an example:

 Collections.sort(listName, new Comparator<Type>() { 	 	 @Override 	 public int compare(Type o1, Type o2) {               // Your sorting logic goes here  	 }   });   

In this code, Type is the type of object stored in the list, and o1 and o2 are variables representing two items being compared. You can use these variables to compare the two items however you like and then return -1, 0 or 1 depending on whether the first item is less than, equal to or greater than the second item.

When sorting a list, it is important to consider the order of the items. For example, if you are sorting a list of numbers, you may want to sort them in ascending or descending order. You can use the Comparator object to specify the order in which the items should be sorted.

Searching a Java List

You can search through a Java list using the binarySearch() method. This method takes two arguments – a Comparator object and the item you are searching for – and returns the index of the item if it is found or -1 if it is not found:

  int index = Collections.binarySearch(listName, item, new Comparator<Type>() { 	 	 @Override 	 public int compare(Type o1, Type o2) {               // Your sorting logic goes here  	 }   });   

In this code, Type is the type of object stored in the list, item is the item you are searching for, and o1 and o2 are variables representing two items being compared.

Conclusion

Java lists are a powerful and versatile data structure that allows you to store and manage collections of objects. In this article we have looked at how to create, manipulate, search and sort a Java list. With this information in hand you should now have a better understanding of how to use Java lists.

Picture of Sarang Sharma

Sarang Sharma

Sarang Sharma is Software Engineer at Bito with a robust background in distributed systems, chatbots, large language models (LLMs), and SaaS technologies. With over six years of experience, Sarang has demonstrated expertise as a lead software engineer and backend engineer, primarily focusing on software infrastructure and design. Before joining Bito, he significantly contributed to Engati, where he played a pivotal role in enhancing and developing advanced software solutions. His career began with foundational experiences as an intern, including a notable project at the Indian Institute of Technology, Delhi, to develop an assistive website for the visually challenged.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Get Bito for IDE of your choice