什么是ArrayList优于Java中的数组? [英] When is an ArrayList preferable to an array in Java?

查看:201
本文介绍了什么是ArrayList优于Java中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中什么时候应该使用ArrayList?何时应该使用数组?

解决方案

p>


  • 数组在它们的大小上是不可变的,你不能轻易地删除和删除元素,而使用ArrayList是很简单的

  • 数组比ArrayList更快(作为特殊对象直接由JVM处理),并且需要更少的内存

  • 数组有一个不错的语法用于访问元素(例如 a [i] vs a.get(i)


  • 数组不能很容易地作为ArrayList包装(例如 Collections utils like checkedList code>和 unmodifiableList

  • code> List 你可以轻松地用 LinkedList 交换实现;这个imho是比普通数组最好的优势

  • 数组 toString equals hashCode 很奇怪,容易出错,您必须使用数组类实用程序


When should I use an ArrayList in Java, and when should I use an array?

解决方案

Some differences:

  • Arrays are immutable in their size, you cannot easly remove and element and remove the hole whereas using an ArrayList is straightforward
  • Arrays are fast (handled directly by the JVM as special objects) than an ArrayList and requires less memory
  • Arrays have a nice syntax for accessing elements (e.g. a[i] vs a.get(i))
  • Arrays don't play well with generics (e.g. you cannot create a generic array)
  • Arrays cannot be easly wrapped as ArrayList (e.g. Collections utils like checkedList, synchronizedList and unmodifiableList)
  • declaring the ArrayList as List you can easly swap implementation with a LinkedList when you need; this imho is the best advantage over plain arrays
  • Array's toString, equals and hashCode are weird and error-prone, you must use Arrays class utilities

这篇关于什么是ArrayList优于Java中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆