1

I am a teachers assistant for a class that teaches Scala. As an assignment, I want the students to implement an arraylist class.

In java I wrote it like:

public class ArrayList<T> implements List<T>{....} 

Is there any equivalent List trait that I should use to implement the arraylist?

0

4 Answers 4

3

The name ArrayList suggests that you should mix-in IndexedSeq. Actually you probably want to get all the goodies that are provided by IndexedSeqLike, i.e.

class ArrayList[A] extends IndexedSeq[A] with IndexedSeqLike[A, ArrayList[A]]

This gets you concrete implementations of head, tail, take, drop, filter, etc. If you also want map, flatMap, etc. (all the methods that take a type parameter) to work properly (return an ArrayList[A]), you also have to provide a type class instance for CanBuildFrom in your companion object, e.g.

def cbf[A, B] = new CanBuildFrom[ArrayList[A], B, ArrayList[B]] {
  // TODO Implementation!
}
Sign up to request clarification or add additional context in comments.

Comments

2

The scala collection library is very complex. For an overview on the inheritance take a look at these pictures:

scala.collection.immutable: http://www.scala-lang.org/docu/files/collections-api/collections.immutable.png

scala.collection.mutable: http://www.scala-lang.org/docu/files/collections-api/collections.mutable.png

Also the scaladoc gives a good overview about all the classes and traits of the collection library.

Be aware, that in Scala a List is a real list, meaning it is a LinearSeq, in Java a List is more like an IndexedSeq in Scala.

2 Comments

I think Scala ArrayBuffers behave like Java ArrayLists.
Vector in Scala is an immutable tree implementation of IndexedSeq; Java's List interface is like Scala's Seq trait
1

In Scala there are many Interfaces. First, they are separated in mutable and immutable ones. In Java ArrayList is based on an array - thus it is an indexed sequence. In Scala the interface for this is IndexedSeq[A]. Because ArrayList is also mutable, you can choose scala.collection.mutable.IndexedSeq otherwise scala.collection.immutable.IndexedSeq. Instead of mutable.IndexedSeq you can also choose scala.collection.mutable.Buffer, which does not guarantee an access time of O(1).

If you wanna have a more functional approach you can prefer Seq[A] as interface or Iterable[A] if you want to be able to implement more than Sequences.

Comments

0

That would be Seq[T], or maybe IndexedSeq[T] - or even List[T].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.