How do I implement the following data ?
somelisttype <int>obj ;
obj 0,0 => val0
obj 0,1 => val1
obj 0,2 => val2
obj 1,0 => val8
obj 2,0 => val9
obj 2,1 => val10
0,0 ; 0,1
are the keys ( or in other way the row index or column index.)
I would like to have following functionality ..
obj 0.add(val11) == obj 0,3 => val11
obj 3.add(val12) == obj 3,0 => val12
obj 2.length => 2
obj 3.length => 1开发者_运维问答
obj 0,2 => val2
ValXX => are values and not objects ( would be integers )
I don't want to create 2d array since I don't know length of total obj or individual obj0,obj1
What variable type can be used for this in android ??
What's about List<List<Integer>>
?
You can't avoid the generic type to be an object here but since cast from Integer
to int
is implicit you would see any difference in use.
Update
Okay here it is:
MyList l = new MyList();
l.set(0, 0, 1);
l.set(1, 0, 2);
l.set(1, 1, 3);
Log.d("TAG", l.get(0, 0) + " " + l.get(1, 0) + " " + l.get(1, 1));
Here the implementation (o course you have to make sure that used index is right, so you can't add index 1 when 0 is not already set):
class MyList {
private List<List<Integer>> mList = new ArrayList<List<Integer>>();
public void set(int i, int k, int value) {
List<Integer> list;
if (i == mList.size()) {
list = new ArrayList<Integer>();
mList.add(i, list);
} else {
list = mList.get(i);
}
if (k == list.size()) {
list.add(value);
} else {
list.set(k, value);
}
}
public int get(int i, int k) {
return mList.get(i).get(k);
}
}
You can use HashMap which is based on key value pair.
You find a simple eg over here.
This is really a basic Java question, and has little to do with Android. You might want to change your tags to get better answers. A List
of List<Integer>
will probably do, unless you need to put/get by key, in which case you need a HashMap
with a composite key, that holds two integers.
精彩评论