简体   繁体   中英

How can I move list Entries with simultaneously updating the index of all Entries?

I need to do the following with a Java/Grails GORM application.

I have a domain class Item:

class Item {

   int position
   String name

}

When I create a list of items I can update the position attribute such that it represents the index of each item in the list: 0,1,2,3,... Each position is unique, ie, at each position can only be one item.

It should be able to change the order of the items. Let's assume I have the following list of items and there positions:

A1, A2, A3, A4, A5
1   2   3   4   5 

When I want A4 to be at position 2 I have to update the positions of A2, A3 and respectively. This means that I have to update three data base entries A4, A2 and A3. If the list is very long then there are a lot of updates to do.

  1. Is there a data structure which handler the repositioning of list elements for me?
  2. How can I update the items efficiently?

Since your int position will always be in order, you can forget about that and use the data structure's index to get your position. (Just add 1, since the index begins at 0). Use either a LinkedList<String> or an ArrayList<String> . They will be almost identical - either way, you are going to have some type of O(n) operation. You won't be able to get around having to traverse the list.

Rather than go into more detail about the efficiency of each data structure, this post gives a very thorough summary.

It sounds like you need a way to identify the list items across a network. Have you considered itentifying the elements with a UUID instead of the list index? That way, you don't have to modify the ID of the element when the order of the list changes. You can get a new UUID by calling

UUID.randomUUID()

As for ordering elements automatically, that is one of the primary responsibilities of a list. If you don't have a list, the elements will need to know of each other in order to update the index values, which will probably result in an implementation of an embedded linked list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM