Reputation: 1428
i need to maintain a list containing two values of string type say v1,v2 for each key say k. What is a better option
I am creating an android app, so just concern about performance. In second case i can access directly but each value will contain another array ( i dont know but it appears like a complicated way) , while in 1st case it will use split function on every access like v.split(",")[0]
Please guide me.
Map<String,String[]> listMap= new HashMap<String, String[]>();
Map<String,String> listMap1= new HashMap<String, String>();;
for (int i = 1; i < tl.getChildCount(); i++) {
TableRow row = (TableRow) tl.getChildAt(i);
COLOR_TABLE clr = (COLOR_TABLE) row.getTag();
if (clr == COLOR_TABLE.green) {
//comp
String x1=listMap1.get( ((TextView) row.getChildAt(0)).getText());
String x2=listMap.get( ((TextView) row.getChildAt(0)).getText());
// now i have to add two string values in a list seperately
}
}
Upvotes: 1
Views: 113
Reputation: 27632
The string will be much slower than the array, and also have more complicated code. (With the caveat that it is hard to be sure about performance differences until one has actually measured it.)
But if it was me, I would use the simplest solution, and use an object. Later, if the program turns out to be too slow, and measurement shows this to be a performance bottleneck, I would consider other solutions.
Upvotes: 1
Reputation: 111219
Using an array or a custom class as the value would be the preferred approach from a design perspective. If you pack two strings into one separated by a character you need to make sure that the first string won't ever contain that same character, or you must use some kind of an escape mechanism to be able to include it.
If you are only worried about performance test all options and pick the best one. It's hard make predictions because the results will depend on the data you store and on how libraries have been implemented. For example, any structure that stores references to independent strings will potentially suffer a cache miss on access; if the string split or a similar method turns out to be cheaper than a cache miss it will be faster.
Upvotes: 0
Reputation: 918
Never abuse Strings! It may be slow at times and they are not made for that purpose.
You could use a generic Pair class if you want to do it more object oriented:
public class Pair<A, B> {
public A first;
public B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
}
Of course you can do it better, with accessors and so.
Upvotes: 5
Reputation: 917
i think split function runs with O(string size) complexity but reach element of an array is a constant
Upvotes: 1