ArrayList.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import Collection from './Collection'
  2. import IndexOutOfBoundsException from '../lang/IndexOutOfBoundsException'
  3. import List from './List'
  4. import NoSuchElementException from './NoSuchElementException'
  5. /**
  6. * @see http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
  7. */
  8. export default class ArrayList extends List {
  9. constructor(o) {
  10. super()
  11. this.array = []
  12. if (o instanceof Collection) this.addAll(o)
  13. }
  14. get interfaces_() {
  15. return [List, Collection]
  16. }
  17. ensureCapacity() { }
  18. add(e) {
  19. if (arguments.length === 1)
  20. this.array.push(e)
  21. else
  22. this.array.splice(arguments[0], 0, arguments[1])
  23. return true
  24. }
  25. clear() {
  26. this.array = []
  27. }
  28. addAll(c) {
  29. for (const e of c)
  30. this.array.push(e)
  31. }
  32. set(index, element) {
  33. const oldElement = this.array[index]
  34. this.array[index] = element
  35. return oldElement
  36. }
  37. iterator() {
  38. return new Iterator(this)
  39. }
  40. get(index) {
  41. if (index < 0 || index >= this.size())
  42. throw new IndexOutOfBoundsException()
  43. return this.array[index]
  44. }
  45. isEmpty() {
  46. return this.array.length === 0
  47. }
  48. sort(comparator) {
  49. if (comparator)
  50. this.array.sort((a, b) => comparator.compare(a, b))
  51. else this.array.sort()
  52. }
  53. size() {
  54. return this.array.length
  55. }
  56. toArray() {
  57. return this.array.slice()
  58. }
  59. remove(o) {
  60. for (let i = 0, len = this.array.length; i < len; i++)
  61. if (this.array[i] === o)
  62. return !!this.array.splice(i, 1)
  63. return false
  64. }
  65. [Symbol.iterator]() {
  66. return this.array.values()
  67. }
  68. }
  69. class Iterator {
  70. constructor(arrayList) {
  71. this.arrayList = arrayList
  72. this.position = 0
  73. }
  74. next() {
  75. if (this.position === this.arrayList.size())
  76. throw new NoSuchElementException()
  77. return this.arrayList.get(this.position++)
  78. }
  79. hasNext() {
  80. return this.position < this.arrayList.size()
  81. }
  82. set(element) {
  83. return this.arrayList.set(this.position - 1, element)
  84. }
  85. remove() {
  86. this.arrayList.remove(this.arrayList.get(this.position))
  87. }
  88. }