迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

在 Java 中从 ArrayList 中获取最后一个元素

作者:迹忆客 最近更新:2023/08/10 浏览次数:

本文介绍了如何从 Java 中的 ArrayList 中获取最后一个元素,并列出了一些示例代码来理解该主题。

ArrayList 是一个动态数组,可用于在有序集合中存储类似数据。Arrays 和 ArrayList 的一个好处是,它们允许随机访问存储在其中的任何元素,前提是我们知道存储元素的索引。但是如果我们不知道它的索引,我们如何访问 ArrayList 的最后一个元素?其他一些语言(如 Python)提供反向索引,因此我们可以使用 -1 来访问最后一个元素。在本教程中,我们将学习如何从 Java 中的 ArrayList 中获取最后一个元素。


使用 size()get() 方法获取最后一个元素

Java 中的 ArrayList 具有 size() 方法,可用于查找 ArrayList 中存在的元素数量。

import java.util.ArrayList;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		System.out.printf("The list contains %d elements", list.size());
	}
}

输出:

The list contains 5 elements

我们知道 ArrayList 的最后一个索引将比它的长度小 1(因为它遵循从零开始的索引)。我们可以使用此信息来获取最后一个元素。我们将使用 ArrayList 的 get() 方法来获取最后一个元素。

import java.util.ArrayList;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		int lastIdx = list.size() - 1;
		int lastElement = list.get(lastIdx);
		System.out.println("The last index of list is: " + lastIdx);
		System.out.print("The last element of list is: " + lastElement);
	}
}

输出:

The last index of list is: 4The last element of list is: 25

让我们写一个通用方法,以避免一次又一次地编写相同的逻辑。

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		int lastIdx = list.size() - 1;
		E lastElement = list.get(lastIdx);
		return lastElement;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		list1.add(5);
		list1.add(10);
		list1.add(15);
		list1.add(20);
		list1.add(25);		
		ArrayList<String> list2 = new ArrayList<String>();
		list2.add("1");
		list2.add("2");
		list2.add("3");		
		System.out.println("The last element of list1 is: " + getLastElement(list1));
		System.out.print("The last element of list2 is: " + getLastElement(list2));
	}
}

输出:

The last element of list1 is: 25
The last element of list2 is: 3

如果我们在一个空的 ArrayList 上运行我们的方法会发生什么?如果我们在一个空列表上运行上面的代码,我们将得到一个 IndexOutOfBoundsException。发生这种情况是因为 size() 方法为空的 ArrayList 返回零,当我们从中减去 1 时,我们得到 -1 作为索引。没有负指数这样的东西。以下示例将返回此异常。

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		int lastIdx = list.size() - 1;
		E lastElement = list.get(lastIdx);
		return lastElement;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		System.out.println("The last element of list1 is: " + getLastElement(list1));
	}
}

在运行 size() 方法之前,让我们检查一些条件。我们将使用 isEmpty() 方法来检查列表是否为空。

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		if((list != null) && (list.isEmpty() == false))
		{
			int lastIdx = list.size() - 1;
			E lastElement = list.get(lastIdx);
			return lastElement;
		}
		else
			return null;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		System.out.println("The last element of list is: " + getLastElement(list));
	}
}

输出:

The last element of list is: null

在 Java 中将 ArrayList 转换为 LinkedList

LinkedList 类,就像 ArrayList,实现了 List 接口。LinkedList 类有一个简单的 getLast() 方法,可用于获取列表的最后一个元素。

如果我们可以将 ArrayList 转换为 LinkedList,那么我们就可以使用这个方法。这个过程不会修改我们原来的 ArrayList

import java.util.ArrayList;
import java.util.LinkedList
public class LastElement
{
	public static <E> E getLastElementUsingLinkedList(ArrayList<E> arrList)
	{
		LinkedList<E> linkedList = new LinkedList<E>(arrList);
		return linkedList.getLast();
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		System.out.println("The last element of list is: " + getLastElementUsingLinkedList(list));
		System.out.print("The array list is: " + list );
	}
}

输出:

The last element of list is: 25
The array list is: [5, 10, 15, 20, 25]

上述解决方案不是获取最后一个元素的优雅方式,不推荐使用。如果我们需要多次访问最后一个元素,那么建议使用 LinkedList(或其他一些集合)而不是 ArrayList。


在 Java 中将 ArrayList 转换为 ArrayDeque

双端队列是双端队列。ArrayDeque 将可调整大小的数组功能与双端队列数据结构相结合。和 LinkedList 一样,ArrayDeque 也有一个方便的 getLast() 方法,可以用来查看双端队列的最后一个元素。我们只需要将 ArrayList 转换为 ArrayDeque 即可使用此方法。

import java.util.ArrayDeque;
import java.util.ArrayList;
public class LastElement
{
	public static <E> Object getLastElementUsingArrayDeque(ArrayList<E> arrList)
	{
		ArrayDeque<E> deque = new ArrayDeque<E>(arrList);
		return deque.getLast();
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);	
		System.out.println("The last element of list is: " + getLastElementUsingArrayDeque(list));
		System.out.print("The array list is: " + list );
	}
}

同样,这个方法不是很优雅,如果我们需要多次访问最后一个元素,那么建议使用 ArrayDeque 而不是 ArrayList。


使用 Guava 库

Google Guava 库提供了一种从 ArrayList 中获取最后一个元素的简单方法。我们将使用该库的 Iterables 类的 getLast() 方法来获取最后一个元素。在运行以下代码之前,请确保下载此库并将其添加到你的项目中。

import java.util.ArrayList;
import com.google.common.collect.Iterables;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);		
		Integer lastEle = Iterables.getLast(list);
		System.out.print("The last element of the array list is: " + lastEle);
	}
}

输出:

The last element of the array list is: 25

我们还可以为 getLast() 方法提供默认值以显示列表是否为空。这将防止 Java 抛出任何异常。

import java.util.ArrayList;
import com.google.common.collect.Iterables;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<String> list = new ArrayList<String>();
		String lastEle = Iterables.getLast(list, "No Element Found");//No Element Found is the             															   default value
		System.out.print("The last element of the array list is: " + lastEle);
	}
}

输出:

The last element of the array list is: No Element Found

总结

ArrayList 是一种非常常见的数据结构,主要用于消除有限大小的普通数组的问题。在很多情况下,我们可能不知道列表的最后一个索引,因此我们找不到存储在其中的最后一个元素。

我们可以使用 size()get() 方法来查看这个元素。Google Guava 库还提供了一种获取最后一个元素的简单方法。

如果我们经常需要访问最后一个元素,最好使用一些其他集合,如 LinkedListArrayDeque,因为这些集合具有所需的方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便