软件构造——接口到底有什么用?

本文探讨了Java接口在提高代码复用性方面的价值,通过比较List接口的两种实现——LinkedList和ArrayList,揭示了不同数据结构对性能的影响。接口允许在不修改代码的情况下切换实现,实现了Strategy策略模式,体现了接口的灵活性和复用性优势。
摘要由CSDN通过智能技术生成

软件构造——接口到底有什么用?

这篇文章是我早就想写的了。

我们都知道,Java的接口是一个很好的提高复用性的手段,也就是说,我们可以采取很多种不同的实现方式来实现一个接口。但是,不同的实现方式到底有什么好处?Talk is cheap,just show code.

这一次用来举例的,是Collection中的List。

Oracle提供的List的Javadoc如下:

public interface List<E> extends Collection<E>

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.

也就是说,List就像是一个数据结构,可以通过用户的操作来对这个数据结构进行增删查改这样的操作。慢着,这些操作好像跟一些常见的数据结构——链表与数组很相似啊。

没错,这些操作在链表与数组上都能实现,而很贴心的是,Java的官方包中也提供了基于链表与基于数组的List实现:LinkedListArrayList,以下是他们的官方文档:

  1. LinkedList

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

  1. ArrayList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

根据上述的文档描述,我们了解到,两种实现基于的是两种不同的数据结构。回忆一下,链表和数组的优缺点都有什么呢?

链表 数组
优点 可动态的添加删除元素,大小是可变的 内存为连续区域,使用方便
缺点 查找特定元素花费的时间更长 大小固定,无法动态的删除增加元素

两种数据结构的特点不同,对应的这两种实现也就不同。接下来就看看运行时间上的差异。

import java.util.LinkedList;
import java.util.List;

public class LinkedListTest {
   
    private List<Long> linkedList = new LinkedList<>();

    public void actionAdd() {
   
        for (long i = 0; i < 1e7; i++
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值