I want to depict the index of elements of an ordered collection in an UML object diagram.
The only information I was able to find in the UML Spec 2.5.1 was in the part about semantics of associations 11.5.3.1.
When one or more ends of the Association are ordered, links carry ordering information in addition to their end values.
But either there is no guidance regarding the notation of such ordering information or I just didn't find it. I think I have seen a colon followed by the index in some tools. I wonder if there is a consensus or reference about how to depict indices on the links?
EDIT:
Although the existing answer is already holistic, let me add some clarification and context. As the first sentence already stated, I want to use this explicit information in an object diagram (maybe the parenthesis were confusing, I removed them). The object diagrams are used as part of test case sepcifications to communicate the object structure of the input, expected result and actual result. To that regard, the order of objects in a collection may play a role, e.g., imagine a test case specification for the correct implementation of the specification of a sorting algorithm.
I did not specify the kind of collection on purpose as I do not see how that would influence the answer as long as the collection is ordered. Typically, a sequence/list would come to my mind.
I do not need OCL in this case but I appreciate the answer taking that into consideration as formulating constraints on the order of collection elements is closely related.
UML
There is nothing foreseen for representing the index of an ordered collection in UML. In section 7.5.3.2 it is defined that ordering makes sense in relation to elements with multiplicity:
If the MultiplicityElement is specified as ordered (i.e., isOrdered is true), then the collection of values in an instantiation of this Element is ordered. This ordering implies that there is a mapping from positive integers to the elements of the collection of values. If a MultiplicityElement is not multivalued, then the value for isOrdered has no semantic effect.
The positive integer that is mapped correspond to what you'd call an index. But nothing is defined in the UML specs: Not even if the index should start at 0, at 1 or at any arbitrary value. It's not even said that the indexes have to be consecutive.
The UML specs explain in the same section, that the semantics of the ordered collections depend also on the unicity of their elements:
isOrdered isUnique Collection Type
false true Set
true true OrderedSet
false false Bag
true false Sequence
Unfortunately, the OrderedSet and Sequence are not defined in the UML specifications.
The only case where the ordering is defined more precisely is for properties defined as derived unions (section 9.5.3):
then the ordering of the union is defined by evaluating the subsetting properties in the order in which they appear in the result of allAttributes() and concatenating the results.
Conclusion: ¨There is no way to define what the order is (e.g. link the order to some properties), and nothing is foreseen to refer to the indexes in the ordering.
OCL
The OCL language is a companion of UML. it is used to write more formal and precise constraints. It defines some more semantics for collections:
The OrderedSet is a Set, the elements of which are ordered. It contains no duplicates. OrderedSet is itself an instance of the metatype OrderedSetType.
An OrderedSet is not a subtype of Set, neither a subtype of Sequence. The common supertype of Sets and OrderedSets is Collection.
A sequence is a collection where the elements are ordered. An element may be part of a sequence more than once. Sequence is itself an instance of the metatype SequenceType.
Sequence is not a subtype of Bag. The common supertype of Sequence and Bag is Collection.
OCL uses the notion of index in several operations available for Sequence and OrderedSet:
The expression at(i) identifies the i-the element
The expression indexOf(v) returns the index of the element v
The expression first() returns the first element, being understood that its index is 1
The expression last() reutrns the last element, being udnerstood that its index correspond to the size of the collection.
These expressions are related to ordered collections and are not defined for unordered collections such as sets and bags.
Conclusion you can use indexes in UML constraints by using OCL and even relate them with the help of constraints an order to properties
Edit: More about object diagrams
Object diagram represents instances of objects. The association lines between these objects hence representthe “links” mentioned in your quote.
While a notation exists to specify values of object properties, nothing is defined for the links:
Pragmatically, you could just number the end of the link (there should be no confusion with multiplicity since it’s a link and not an association). If you fear some confusion, you may prefix the number with an informal # or Nr. .
Alternatively, if you have to stay 100% compliant, you may put the order information in a note symbol.
Reading section 9.8.4 page 126, and considering the use of = to specifiy values within instances, I think that it could be argued that order=1 would be valid, since the only value that is not already defined for the link through the instances at both ends are the ordering information.
I am learning Java 8 newly , i see one definition related to functional programming which is "A program created using only pure functions , No Side effects allowed".
One of side effects is "Modifying a data structure in place".
i don't understand this line because at last some where we need to speak with database for storing or retrieving or updating the data.
modifying database is not functional means how we will speak with database in functional programming ?
"Modifying a data structure structure in place" means you directly manipulate the input datastructure (i.e. a List). "Pure functions" mean
the result is only a function of it's input and not some other hidden state
the function can be applied multiple times on the same input producing the same result. It will not change the input.
In Object Oriented Programming, you define behaviour of objects. Behaviour could be to provide read access to the state of the object, write access to it, or both. When combining operations of different concerns, you could introduce side effects.
For example a Stack and it's pop() operation. It will produce different results for every call because it changes the state of the stack.
In functional programming, you apply functions to immutable values. Functions represent a flow of data, not a change in state. So functions itself are stateless. And the result of a function is either the original input or a different value than the input, but never a modified input.
OO also knows functions, but those aren't pure in all cases, for example sorting: In non-functional programming you rearrange the elements of a list in the original datastructure ("in-place"). In Java, this is what Collections.sort()` does.
In functional programming, you would apply the sort function on an input value (a List) and thereby produce a new value (a new List) with sorted values. The function itself has no state and the state of the input is not modified.
So to generalize: given the same input value, applying a function to this value produces the same result value
Regarding the database operations. The contents of the database itself represent a state, which is the combination of all its stored values, tables etc (a "snapshot"). Of course you could apply a function to this data producing new data. Typically you store results of operations back to the db, thus changing the state of the entire system, but that doesn't mean you change the state of the function nor it's input data. Reapplying the function again, doesn't violate the pure-function constraints, because you apply the data to new input data. But looking at the entire system as a "datastructure" would violate the constraint, because the function application changes the state of the "input".
So the entire database system could hardly be considered functional, but of course you could operate on the data in a functional way.
But Java allows you to do both (OO and FP) and even mix both paradigms, so you could choose whatever approach fits your needs best.
or to quote from this answer
If you have several needs intermixed, mix your paradigms. Do not
restrict yourself to only using the lower right corner of your
toolbox.
While using Graph Databases(my case Neo4j), we can represent the same information many ways. Making each entity a Node and connecting all entities through relationships or just adding the entities to attribute list of a Node.diff
Following are two different representations of the same data.
Overall, which mechanism is suitable in which conditions?
My use case involves traversing the Database from different nodes until 4 depths and examining the information through connected nodes or attributes (based on which approach it is).
One query of interest may be, "Who are the friends of John who went to Stanford?"
What is the difference in terms of Storage, computations
Normally,
properties are loaded lazily, and are more expensive to hold in cache, especially strings. Nodes and Relationships are most effective for traversal, especially since the relationships types are stored together with the relatoinship records and thus don't trigger property loads when used in traversals.
Also, a balanced graph (that is, not many dense nodes with over say 10K relationships) is most effective to traverse.
I would try to model most of the reoccurring proeprties as nodes connecting to the entities, thus using the graph itself to index on these values, instead of having to revert to filter on property values or index the property with an expensive index lookup.
The first one is much better since you're querying on entities such as Stanford- and that entity is related to many person nodes. My opinion that modeling as nodes is more intuitive and easier to query on. "Find all persons who went to Stanford" would not be very easy to do in your second model as you don't have a place to start traversing from.
I'd use attributes mainly to describe the node/entity use them to filter results from the query e.g. Who are friends of John who went to Stanford in the year 2010. In this case, the year attribute would just be used to trim the results. Depends on your use case- if year is really important and drives a lot of queries or is used to represent a timeline, you could even model the year as a node attached to Stanford.
I know a map is a data structure that maps keys to values. Isn't a dictionary the same? What is the difference between a map and a dictionary1?
1. I am not asking for how they are defined in language X or Y (which seems to be what generally people are asking here on SO), I want to know what is their difference in theory.
Two terms for the same thing:
"Map" is used by Java, C++
"Dictionary" is used by .Net, Python
"Associative array" is used by PHP
"Map" is the correct mathematical term, but it is avoided because it has a separate meaning in functional programming.
Some languages use still other terms ("Object" in Javascript, "Hash" in Ruby, "Table" in Lua), but those all have separate meanings in programming too, so I'd avoid them.
See here for more info.
One is an older term for the other. Typically the term "dictionary" was used before the mathematical term "map" took hold. Also, dictionaries tend to have a key type of string, but that's not 100% true everywhere.
Summary of Computer Science terminology:
a dictionary is a data structure representing a set of elements, with insertion, deletion, and tests for membership; the elements may be, but are not necessarily, composed of distinct key and value parts
a map is an associative data structure able to store a set of keys, each associated with one (or sometimes more than one - e.g. C++ multimap) value, with the ability to access and erase existing entries given only the key.
Discussion
Answering this question is complicated by programmers having seen the terms given more specific meanings in particular languages or systems they've used, but the question asks for a language agnostic comparison "in theory", which I'm taking to mean in Computing Science terms.
The terminology explained
The Oxford University Dictionary of Computer Science lists:
dictionary any data structure representing a set of elements that can support the insertion and deletion of elements as well as test for membership
For example, we have a set of elements { A, B, C, D... } that we've been able to insert and could start deleting, and we're able to query "is C present?".
The Computing Science notion of map though is based on the mathematical linguistic term mapping, which the Oxford Dictionary defines as:
mapping An operation that associates each element of a given set (the domain) with one or more elements of a second set (the range).
As such, a map data structure provides a way to go from elements of a given set - known as "keys" in the map, to one or more elements in the second set - known as the associated "value(s)".
The "...or more elements in the second set" aspect can be supported by an implementation is two distinct way:
Many map implementations enforce uniqueness of the keys and only allow each key to be associated with one value, but that value might be able to be a data structure itself containing many values of a simpler data type, e.g. { {1,{"one", "ichi"}, {2, {"two", "ni"}} } illustrates values consisting of pairs/sets of strings.
Other map implementations allow duplicate keys each mapping to the same or different values - which functionally satisfies the "associates...each [key] element...with...more [than one] [value] elements" case. For example, { {1, "one"}, {1, "ichi"}, {2, "two"}, {2, "ni"} }.
Dictionary and map contrasted
So, using the strict Comp Sci terminology above, a dictionary is only a map if the interface happens to support additional operations not required of every dictionary:
the ability to store elements with distinct key and value components
the ability to retrieve and erase the value(s) given only the key
A trivial twist:
a map interface might not directly support a test of whether a {key,value} pair is in the container, which is pedantically a requirement of a dictionary where the elements happen to be {key,value} pairs; a map might not even have a function to test for a key, but at worst you can see if an attempted value-retrieval-by-key succeeds or fails, then if you care you can check if you retrieved an expected value.
Communicate unambiguously to your audience
⚠ Despite all the above, if you use dictionary in the strict Computing Science meaning explained above, don't expect your audience to follow you initially, or be impressed when you share and defend the terminology. The other answers to this question (and their upvotes) show how likely it is that "dictionary" will be synonymous with "map" in the experience of most programmers. Try to pick terminology that will be more widely and unambiguously understood: e.g.
associative container: any container storing key/value pairs with value-retrieval and erasure by key
hash map: a hash table implementation of an associative container
hash set enforcing unique keys: a hash table implementation of a dictionary storing element/values without treating them as containing distinct key/value components, wherein duplicates of the elements can not be inserted
balance binary tree map supporting duplicate keys: ...
Crossreferencing Comp Sci terminology with specific implementations
C++ Standard Library
maps: map, multimap, unordered_map, unordered_multimap
other dictionaries: set, multiset, unordered_set, unordered_multiset
note: with iterators or std::find you can erase an element and test for membership in array, vector, list, deque etc, but the container interfaces don't directly support that because finding an element is spectacularly inefficient at O(N), in some cases insert/erase is inefficient, and supporting those operations undermines the deliberately limited API the container implies - e.g. deques should only support erase/pop at the front and back and not in terms of some key. Having to do more work in code to orchestrate the search gently encourages the programmer to switch to a container data structure with more efficient searching.
...may add other languages later / feel free to edit in...
My 2 cents.
Dictionary is an abstract class in Java whereas Map is an interface. Since, Java does not support multiple inheritances, if a class extends Dictionary, it cannot extend any other class.
Therefore, the Map interface was introduced.
Dictionary class is obsolete and use of Map is preferred.
Typically I assume that a map is backed by a hash table; it connotes an unordered store.
Dictionaries connote an ordered store.
There is a tree-based dictionary called a Trie.
In Lisp, it might look like this:
(a (n (d t)) n d )
Which encapsulates the words:
a
and
ant
an
ad
The traversal from the top to the leaf yields a word.
Not really the same thing. Maps are a subset of dictionary. Dictionary is defined here as having the insert, delete, and find functions. Map as used by Java (according to this) is a dictionary with the requirement that keys mapping to values are strictly mapped as a one-to-one function. A dictionary might have more than one key map to one value, or one key map to several values (like chaining in a hasthtable), eg Twitter hashtag searches.
As a more "real world" example, looking up a word in a dictionary can give us a number of definitions for the same word, and when we find an entry that points us to another entry (see other word), a number of words for the same list of definitions. In the real world, maps are much broader, allowing us to have locations for names or names for coordinates, but also we can find a nearest neighbor or other attributes (populations, etc), so IMHO there could be argument for a greater expansion of the map type to possibly have graph based implementations, but it would be best to always assume just the key-value pair, especially since nearest neighbor and other attributes to the value could all just be data members of the value.
java maps, despite the one-to-one requirement, can implement something more like a generalized dictionary if the value is generalized as a collection itself, or if the values are merely references to collections stored elsewhere.
Remember that Java maintainers are not the maintainers of ADT definitions, and that Java decisions are specifically for Java.
Other terms for this concept that are fairly common: associative array and hash.
Yes, they are the same, you may add "Associative Array" to the mix.
using Hashtable or a Hash ofter refers to the implementation.
These are two different terms for the same concept.
Hashtable and HashMap also refer to the same concept.
so on a purely theoretical level.
A Dictionary is a value that can be used to locate a Linked Value.
A Map is a Value that provides instructions on how to locate another values
all collections that allow non linear access (ie only get first or get last) are a Map, as even a simple Array has an index that maps to the correct value. So while a Dictionary is a Type of map, maps are a much broader range of possible function.
In Practice a its usually the mapping function that defines the name, so a HashMap is a mapped data structure that uses a hashing algorithm to link the key to the value, where as a Dictionary doesn't specify how the keys are linked to a value so could be stored via a linked list, tree or any other algorithm. from the usage end you usually don't care what the algorithm only that they work so you use a generic dictionary and only shift to one of the other structures only when you need to enfore the type of algorithm
The main difference is that a Map, requires that all entries(value & key pair) have a unique key. If collisions occur, i.e. when a new entry has the same key as an entry already in the collection, then collision handling is required.
Usually, we handle collisions using either Separate Chaining. Or Linear Probing.
A Dictionary allows for multiple entries to be linked to the same key.
When a Map has implemented Separate Chaining, then it tends to resemble a Dictionary.
I'm in a data structures class right now and my understanding is the dict() data type that can also be initialized as just dictionary = {} or with keys and values, is basically the same as how the list/array data type is used to implement stacks and queues. So, dict() is the type and maps are a resulting data structure you can choose to implement with the dictionary data type in the same way you can use the list type and choose to implement a stack or queue data structure with it.
I would like to know a few practical use-cases (if they are not related/tied to any programming language it will be better).I can associate Sets, Lists and Maps to practical use cases.
For example if you wanted a glossary of a book where terms that you want are listed alphabetically and a location/page number is the value, you would use the collection TreeMap(OrderedMap which is a Map)
Somehow, I can't associate MultiSets with any "practical" usecase. Does someone know of any uses?
http://en.wikipedia.org/wiki/Multiset does not tell me enough :)
PS: If you guys think this should be community-wiki'ed it is okay. The only reason I did not do it was "There is a clear objective way to answer this question".
Lots of applications. For example, imagine a shopping cart. That can contain more than one instance of an item - i.e. 2 cpu's, 3 graphics boards, etc. So it is a Multi-set. One simple implementation is to also keep track of the number of items of each - i.e. keep around the info 2 cpu's, 3 graphics boards, etc.
I'm sure you can think of lots of other applications.
A multiset is useful in many situations in which you'd otherwise have a Map. Here are three examples.
Suppose you have a class Foo with an accessor getType(), and you want to know, for a collection of Foo instances, how many have each type.
Similarly, a system could perform various actions, and you could use a Multiset to keep track of how many times each action occurred.
Finally, to determine whether two collections contain the same elements, ignoring order but paying attention to how often instances are repeated, simply call
HashMultiset.create(collection1).equals(HashMultiset.create(collection2))
In some fields of Math, a set is treated as a multiset for all purposes. For example, in Linear Algebra, a set of vectors is teated as a multiset when testing for linear dependancy.
Thus, implementations of these fields should benefit from the usage of multisets.
You may say linear algebra isn't practical, but that is a whole different debate...
A Shopping Cart is a MultiSet. You can put several instances of the same item in a Shopping Cart when you want to buy more than one.