Skip to content

LinearCollectionPage

gcx edited this page Nov 30, 2020 · 7 revisions

Object

Since there is no concept of generics in golang yet, Object(equals to interface{}) is defined to represent the element in collection. An element must be converted to Object before added to the collection, and can be converted to its real type by type assertions after removed. An object may represent an element of any type, a collection may contain different types of elements (not suggested).

Collection

The interfaces of commonly used collection types are defined in collection.go, such as list, map, and so on. Most collections are belong to linear collection except Map (shown on the next Page). These interfaces and their implements are as follows:

Interface Implement
List ArrayList, LinkedList
Stack LinkedList
Queue LinkedList, PriorityQueue
Deque LinkedList, ArrayDeque
Set HashSet
SortedSet SortedSet
SortedMap SkipListMap

ArrayList

Method New, which defined in every collection, are recommended to create a new container:

var l = arraylist.New()

After array list is created, we can use Append adds the specified element to the end of this list:

var a collection.Object = Student{1, "Alice"}
var b collection.Object = Student{2, "Bob"}
l.Append(&a)
l.Append(&b)

As mentioned in the previous article, you must use type assertion to convert the element to its real type after you get it from collection. Remember all the elements are represented as Object!

var p = l.Get(1)
var _ = (*p).(Student)

LinkedList

ArrayList is not as powerful as LinkedList in some aspects, the latter implements not only List, but also Stack, Queue and Deque. You must choose LinkedList if you want to use certain methods of Stack or Queue.

// init
var l = linkedlist.New()
// add
var a collection.Object = Student{1, "Alice"}
l.Append(&a)
// stack operation
var b collection.Object = Student{2, "Bob"}
l.Push(&b)
var p1 = l.Pop()
var _ = (*p1).(Student)
// queue operation
var p2 = l.First()
var _ = (*p2).(Student)
// deque operation
var p3 = l.RemoveFirst()
var _ = (*p3).(Student)

PriorityQueue

The elements of the priority queue are ordered according to the specific parameter 'precede', which must be pre-defined before creating a new PriorityQueue.

// init
var precede = func(p1 *collection.Object, p2 *collection.Object) bool {
	s1 := (*p1).(Student)
	s2 := (*p2).(Student)
	return s1.Id < s2.Id
}
var q = priorityqueue.New(precede)
// add
var a collection.Object = Student{1, "Alice"}
var b collection.Object = Student{2, "Alice"}
q.Add(&a)
q.Add(&b)
// poll
var p = q.Poll()
var _ = (*p).(Student)

ArrayDeque

HashSet

SortedSet

You may find more examples from the tests in source code package.

Clone this wiki locally