0

Is there a builtin data structure in java that lets me do this:

Matrix matrix = new Matrix(); // No fixed size, and O(1) to initate

matrix.set(x,y,32); // adds 32 to arbitrary positions x and y in O(1)
matrix.isempty(x,y); // returns true or false wether x,y has been set to a value
matrix.clear(); // clears all elements in O(1)

You cannot use a two dimensional array, because you need to initate it to a fixed size, which takes O(x*y). You cannot use a list of lists, because you cannot add objects to arbitrary positions.

3
  • 1
    I would use a HashMap, or TObjectIntHashMap unless you have a more specific requirement. BTW There is libraries like Colt which support sparse arrays/matricies. Commented Sep 24, 2014 at 19:52
  • 2
    The second-person imperative implies this is homework. Some people mind this. I however do not =D Commented Sep 24, 2014 at 19:53
  • 1
    I see nowhere where you set the size. Is there any concept of "reading off the end"? Commented Sep 24, 2014 at 19:53

2 Answers 2

2

Have a look at Google Guava's collection class Table. Might be an option unless this class is too heavyweight for you.

Sign up to request clarification or add additional context in comments.

3 Comments

OP says they're looking for "a builtin data structure" or else I would have recommended the same thing.
@DanO : Maybe built-in means "I don't want to implement it myself". I think this is a quite good answer.
Indeed. I missed that. Hopefully, it helps anyway :)
0

Considering just these operations, you could implement it thanks to a HashMap<java.awt.Point,SomeType>, but I don't think it already exists this way.

2 Comments

@ScottHunter : Nothing in the doc enables me to be positive about that but knowing the general implementation details of HashMap, I think that clear only consists in allocating a new array and updating some fields.
I could be wrong, I just saw an implementation of HashMap that keeps the same capacity after clear, so it has to set all the values of the table to null, which is a O(n).

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.