List items ordering problem
I have a list of items and set of users. Users can re-order list items. Each user has his own view开发者_如何学JAVA for the list, he can arrange the items in his own way. One item can be placed in different locations in list for different users. I've to track the item location for users in list item. Please give a suggestion to implement this. The size of the list is not constant. I'm using Java. My intension is I have to show the list for every user in their ordering format. Please Masters give me a suggestion.
You can keep an ordered list of, well, the order to retrieve items from your master list:
List<Foo> items = new ArrayList<Foo>();
// add stuff to items (say, 6 things)
Map<String,List<Integer>> userOrders = new HashMap<String,List<Integer>>();
userOrders.put("A", Arrays.asList(0,1,2,3,4,5)); // add user A's order
userOrders.put("B", Arrays.asList(5,4,3,2,1,0)); // add user B's order
// display for userA:
for(Integer i : userOrders.get("A")){
show(items.get(i)); // show the userA's i-th item
}
Here I'm also using a Map
to hold the orders. Depending on your application you might use some other scheme to retrieve the user's custom ordering, but the principle will always be the same: if the user can have a custom order, you should store that ordering somewhere, and then iterate through the list of things based on that ordering (as shown above).
Also take care with the type of List
you're using, calling get
for random access on a LinkedList
is substantially more costly than on an ArrayList
.
Why don't you do a classic Object Oriented Design for this first, as suggested by glowcoder. Then you will have User class and Item class. User class will have a list of Item instances.
class User{
String userId;
List<Item> userItems;
}
A reverse structure would reflect in the database as well (User Table, Item Table and a User-Item Table with foreign key mappings to the first two tables). The Map of List solution suggested by Mark works, but is not the 'correct' approach in an object oriented language like Java.
You have one location that stores the actual list of items. Then each user gets their own model of the data. It is backed by the actual list, but model is more of a mapping between the actual indexes of each item and the display index the user has for the item. Then you have one viewer that can use the model to display the list in the GUI. As far as the viewer is concerned, the model is telling it the correct indexes. But the model allows for the conversion from displayed order to real order. As the user manipulates the list through the view, you update the index map and never touch the actual data.
精彩评论