- add swap method to arraylist (consider adding this on all lists)

pull/1/head
Emir Pasic 9 years ago
parent 133677039b
commit 092a115642

@ -168,13 +168,14 @@ func main() {
list := arraylist.New()
list.Add("a") // ["a"]
list.Add("c", "b") // ["a","c","b"]
list.Sort(utils.StringComparator) // ["a","b","c"]
list.Sort(utils.StringComparator) // ["a","b","c"]
_, _ = list.Get(0) // "a",true
_, _ = list.Get(100) // nil,false
_ = list.Contains("a", "b", "c") // true
_ = list.Contains("a", "b", "c", "d") // false
list.Remove(2) // ["a","b"]
list.Remove(1) // ["a"]
list.Swap(0, 1) // ["b","a",c"]
list.Remove(2) // ["b","a"]
list.Remove(1) // ["b"]
list.Remove(0) // []
list.Remove(0) // [] (ignored)
_ = list.Empty() // true

@ -40,8 +40,9 @@ func ArrayListExample() {
_, _ = list.Get(100) // nil,false
_ = list.Contains("a", "b", "c") // true
_ = list.Contains("a", "b", "c", "d") // false
list.Remove(2) // ["a","b"]
list.Remove(1) // ["a"]
list.Swap(0, 1) // ["b","a",c"]
list.Remove(2) // ["b","a"]
list.Remove(1) // ["b"]
list.Remove(0) // []
list.Remove(0) // [] (ignored)
_ = list.Empty() // true

@ -142,6 +142,13 @@ func (list *List) Sort(comparator utils.Comparator) {
utils.Sort(list.elements[:list.size], comparator)
}
// Swaps two elements with the given indices.
func (list *List) Swap(i, j int) {
if list.withinRange(i) && list.withinRange(j) {
list.elements[i], list.elements[j] = list.elements[j], list.elements[i]
}
}
func (list *List) String() string {
str := "ArrayList\n"
values := []string{}

@ -73,6 +73,13 @@ func TestArrayList(t *testing.T) {
t.Errorf("Got %v expected %v", actualValue, "c")
}
list.Swap(0, 1)
if actualValue, ok := list.Get(0); actualValue != "b" || !ok {
t.Errorf("Got %v expected %v", actualValue, "c")
}
list.Remove(2)
if actualValue, ok := list.Get(2); actualValue != nil || ok {

Loading…
Cancel
Save