What is the most elegant way to copy keys and values from one hashtable to another between start and end keys in inverse order? For example original hashtable is:
[<1,"object1">; <2, "object2">; <4,"object3">; <5,"object4">;<7,"object5">;<8,"object6">]
after calling function getPartListOfNews(2,4) it should return hashtable like this:
[<7,"object5">;<5,"object4">;<4,"object3">]
I had made code to do it and it comes below, but I don’t think is this a better way to do what i had described before. Is there ara any better solutions? How can I simplify this code?
public Hashtable<Integer, News> getPartListOfNews(int start, int end){
Hashtable <Integer, News> tempNewsList = new Hashtable <Integer, News>();
int total_to_get = end-start;
int list_size = newsList.size();
Object[] key_array = new Object[list_size];
if(list_size < total_to_get){
return newsList;
}
else{
Enumeration e = newsList.keys();
int index=0;
while(e.hasMoreElements()){
key_array[index] = e.nextElement();
index ;
}
for (int i=end; i>start; i--){
tempNewsList.put((Integer)key_array[i], newsList.get(key_array[i]));
}
return tempNewsList;
}
}
Update:
public Hashtable<Integer, News> newsList = new Hashtable<Integer, News>();
Thanks.
First, you need to use a
LinkedHashMapin yournewsListattribute, to preserve insertion order. Also, it’s better if you declare attributes and return values of methods using theMapinterface instead of the concrete class used, in this way you can easily change the implementation, like this:With the above in mind, here’s my shot at solving your problem: