gpt4 book ai didi

java - 接口(interface)引用和具体类引用之间的区别

转载 作者:行者123 更新时间:2023-12-02 05:18:26 24 4
gpt4 key购买 nike

我想问一个关于使用 List 的问题在java的Collections API中:

List <Integer> list = new ArrayList<>();
ArrayList<Integer> aList = new ArrayList<>();

我们可以使用其中任何一个来制作 ArrayList 的对象,那么这是创建 ArrayList 的更好方法,为什么?

最佳答案

第一个选项使代码的其余部分更加模块化,因为您可以通过更改一行代码来替换代码使用的 List 实现。

你只需要改变

List <Integer> list = new ArrayList<>();

List <Integer> list = new SomeOtherListImplementation<>();

将变量声明为 ArrayList 会将您的代码与 List 接口(interface)的 ArrayList 实现联系起来。

但是,如果您的代码需要使用不属于 List 接口(interface)的 ArrayList 方法,则可能必须使用 ArrayList 变量。

关于java - 接口(interface)引用和具体类引用之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26709982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com