github.com/tursom/GoCollections@v0.3.10/util/arrayList.go (about)

     1  /*
     2   * Copyright (c) 2022 tursom. All rights reserved.
     3   * Use of this source code is governed by a GPL-3
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package util
     8  
     9  import (
    10  	"github.com/tursom/GoCollections/collections"
    11  	"github.com/tursom/GoCollections/exceptions"
    12  	"github.com/tursom/GoCollections/lang"
    13  )
    14  
    15  type arrayList[T lang.Object] struct {
    16  	lang.BaseObject
    17  	array []T
    18  }
    19  
    20  func (a *arrayList[T]) ListIterator() collections.ListIterator[T] {
    21  	return &arrayListIterator[T]{a.array, 0}
    22  }
    23  
    24  func (a *arrayList[T]) Iterator() collections.Iterator[T] {
    25  	return a.ListIterator()
    26  }
    27  
    28  func (a *arrayList[T]) Size() int {
    29  	return lang.Len(a.array)
    30  }
    31  
    32  func (a *arrayList[T]) IsEmpty() bool {
    33  	return a.Size() == 0
    34  }
    35  
    36  func (a *arrayList[T]) Contains(element T) bool {
    37  	return collections.Contains[T](a, element)
    38  }
    39  
    40  func (a *arrayList[T]) ContainsAll(c collections.Collection[T]) bool {
    41  	return collections.ContainsAll[T](a, c)
    42  }
    43  
    44  func (a *arrayList[T]) Get(index int) (T, exceptions.Exception) {
    45  	return CheckedGet(a.array, index)
    46  }
    47  
    48  func (a *arrayList[T]) SubList(from, to int) collections.List[T] {
    49  	return &arrayList[T]{array: a.array[from:to]}
    50  }
    51  
    52  type arrayListIterator[T lang.Object] struct {
    53  	array []T
    54  	index int
    55  }
    56  
    57  func (a *arrayListIterator[T]) HasPrevious() bool {
    58  	return a.index > 0
    59  }
    60  
    61  func (a *arrayListIterator[T]) Previous() (T, exceptions.Exception) {
    62  	a.index--
    63  	return a.array[a.index], nil
    64  }
    65  
    66  func (a *arrayListIterator[T]) NextIndex() int {
    67  	return a.index
    68  }
    69  
    70  func (a *arrayListIterator[T]) PreviousIndex() int {
    71  	return a.index - 1
    72  }
    73  
    74  func (a *arrayListIterator[T]) HasNext() bool {
    75  	return a.index < lang.Len(a.array)
    76  }
    77  
    78  func (a *arrayListIterator[T]) Next() (r T, err exceptions.Exception) {
    79  	defer func() {
    80  		r := recover()
    81  		if r != nil {
    82  			err = exceptions.NewNPE("", exceptions.Cfg().SetCause(r))
    83  		}
    84  	}()
    85  	i := a.index
    86  	a.index++
    87  	r = a.array[i]
    88  	return
    89  }