I planned to make a wrapper to Swift MT203, MT204 messages.
Message Structure as follows,
MT203 -
2 Mandatory Sequences, where first one exists once and second one can exists two to ten times, and each sequence can contains mandatory fields and optional fields.
MT204 -
2 Mandatory Sequences, where first one exists once and second one can exists more than one time, and each sequence can contains mandatory fields and optional fields.
[References for the MT203 and MT204]
https://www2.swift.com/knowledgecentre/publications/usgf_20180720/1.0?topic=finmt203.htm
https://www2.swift.com/knowledgecentre/publications/usgf_20180720/1.0?topic=finmt204.htm
Which data structure is better to use to store the second sequences in each cases,
I prefer, Array for instance MT203, since I know the maximum size of second sequence but for MT204 I was confused to choose which is better from array and array list.
As during unpacking we have to get fields continuously but not all fields are mandatory for the second sequences.
[Also do comment if the first one choice of Array is not valid]
I think you'd do quite fine with either data structures.
Having said that, there's some things you might want to consider: you can make an ArrayList (like any other list) Immutable. That will prevent unwanted modification of the contents. This might be very interesting when you pass these message objects around and want to prevent someone else to modify the message accidentally. There's many ways to make a list immutable - such as Collections.immutableList(myArrayList) or Guava's ImmutableList.copyOf(myArrayList).
Having said that, I believe that there are more important considerations than features of lists over features of array:
First of all, I would consider having them both use the same data structure - especially if both messages are used in the same part of the codebase, it's going to be very confusing if one message type is an array, while the other one is a list. This might ultimately become a pain in the back as both messages will have to be handled differently. e.g. if you want to log messages - you'll have to do that differently for lists vs arrays.
Secondly, I would recommend, modelling each of these messages as a class. That class would (obviousely) use an array or a list internally to store the message data, but it would also give higher level semantical access to the contents of the message.
say you wanted the ValueDate of MTS203 (field index 1): you'd always need to call dateFormat.parse(message[1]) for that - and everyone would need to remember what index 1 was and how to parse the date string into an actual date object. If you had a class like this:
class MultipleGeneralFinancialInstitutionTransfer {
private List<String> messageData;
/** constructor... */
public Date getValueDate() {
return parseDate(messageData.get(1)); // imagine parse date being a method to parse the actual format
}
}
it would be much more convenient to work with that message - and nobody would need to remember the actual format of that message.
I. Size: Array in Java is fixed in size. We can not change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically.
II. Performance: In Java Array and ArrayList give different performance for different operations.
add() or get(): Adding an element to or retrieving an element from an array or ArrayList object has similar performance. These are constant time operations.
resize(): Automatic resize of ArrayList slows down the performance. ArrayList is internally backed by an Array. In resize() a temporary array is used to copy elements from old array to new array.
III. Primitives: Array can contain both primitive data types as well as objects. But ArrayList can not contain primitive data types. It contains only objects.
IV. Iterator: In an ArrayList we use an Iterator object to traverse the elements. We use for loop for iterating elements in an array.
V. Type Safety: Java helps in ensuring Type Safety of elements in an ArrayList by using Generics. An Array can contain objects of same type of classe. If we try to store a different data type object in an Array then it throws ArrayStoreException.
VI. Length: Size of ArrayList can be obtained by using size() method. Every array object has length variable that is same as the length/size of the array.
VII. Adding elements: In an ArrayList we can use add() method to add objects. In an Array assignment operator is used for adding elements.
VIII. Multi-dimension: An Array can be multi-dimensional. An ArrayList is always of single dimension
Now you can chose as per your need which is better for you
Related
I know Java and also recently started learning Python. At one point I understood that I need to take a pause and clarify all questions related to Data Structures, especially Lists, Arrays and Tuples. Could you please correct me if I am wrong in any of the following:
Originally, according to Data Structures standards, Lists do not
support any kind of indexation. The only way to get access to the
element is through iterations (next method).
In Java there is actually a way to get access to elements by index (i.e. get(index) method), but even if you use these index-related methods it is still iterating from the first element (or more specifically its reference)
There is a way in Python to access to Lists elements as we work with arrays in Java, using list[index] syntax, but in reality, even though this data type is called "lists", we do have an array of references in the background and when we refer to the third element, for example, we are referring directly to the 3 element in array to get reference without iteration from the first one (I am pretty sure that I am wrong over here)
Tuples are implemented in the same way as Lists in Python. The only difference is that they are immutable. But it is still something closer to lists than arrays, because elements are not located contiguously in memory.
There are no arrays as in Python
In Data Structure theory, when we are creating an array, it uses only a reference to the first cell of memory, and then iterates to the # of element that we specified as index. The main difference between Lists and Arrays is that all elements are located contiguously in memory, that's why we are winning in performance aspect.
I am pretty sure that I am wrong somewhere. Could you correct me please?
Thanks
Most of that is wrong.
The list abstract data type is an ordered sequence of elements, allowing duplicates. There are many ways to implement this data type, particularly as a linked list, but most programming languages use dynamically resized arrays.
Even linked lists may support indexing. There is no way for the implementation to skip directly to the n'th element, but it can just follow links to get there.
Java's List type does not specify an implementation, only an interface. The ArrayList type is a List implemented with a dynamic array; the Linkedlist is exactly what the name says.
Python's lists are implemented with dynamically resized arrays. Python's tuples are implemented with fixed-size arrays.
There are actually two Python types commonly referred to as arrays, not counting the common newbie usage of "array" to refer to Python lists. There are the arrays provided by the array module, and there are NumPy's ndarrays.
When you index an array, the implementation does not iterate from the location of the first element to the n'th. It adds an offset to the address of the array to skip to the element directly, without iterating.
Is an ArrayList is just the interface for a dynamic array? Or are they the same thing?
like: ArrayList corresponds to dynamic array, HashMap corresponds to Map ?
except I don't see any Java API for something like a dynamic array, unless it is ArrayList?
Yes. In short. A longer explanation is that an ArrayList is a collection that uses arrays for storage, rather than a linked list, doubly linked list or similar. This means that it gives all the benefits of using an Array, whilst Java looks after the mechanics of sizing the Array for you (dynamically).
I seem to remember that the initial array is created with a default maximum size (which can be specified by the user). Should the collection run out of space, then a larger array is created and the contents of the original array copied into the new one. The increment in size is set to prevent this happening too often, as the operation is fairly costly.
Java also offers the Vector collection which is similar, but is also thread safe, see: What are the differences between ArrayList and Vector?.
ArrayList is the resizable-array implementation of the List interface.
So that's probably what you are looking for if you need a dynamic array.
ArrayList is not a dynamic array, it's not an array type dynamic or not, it's just one of the implementations of the List interface. Understand the difference between classes and interfaces. On the other hand arrays are container objects with the fixed size.
If in the dynamic sense you mean an array which can change in size then a List is an interface for a dynamic array. It is named ArrayList because it uses an array internally that's all.
Your analogy does not fit in the java collections framework since you can say that an ArrayList is a dynamic array but Map (or HashMap for that matter) does not have a "primitive" counterpart.
If by 'dynamic array' you mean an array in C++, then all arrays in Java are dynamic and stored on heap. ArrayList is a resizable wrapper for it. It also provides simple consistency checks - i.e. that you don't modify your array from outside during iteration.
I want to create a large matrix (n by n) where each element corresponds to a LinkedList (of certain objects).
I can either
Create the n*n individual linked lists and name them with the help of eval() within a loop that iterates through both dimensions (or something similar), so that in the end I'll have LinkedList_1_1, LinkedList_1_2 etc. Each one has a unique variable name. Basically, skipping the matrix altogether.
Create an ArrayList of ArrayLists and then push into each element a linked list.
Please recommend me a method if I want to conserve time & space, and ease-of-access in my later code, when I want to reference individual LinkedLists. Ease-of-acess will be poor with Method 1, as I'll have to use eval whenever I want to access a particular linked list.
My gut-feeling tells me Method 2 is the best approach, but how exactly do I form my initializations?
As you know the sizes to start with, why don't you just use an array? Unfortunately Java generics prevents the array element itself from being a concrete generic type, but you can use a wildcard:
LinkedList<?>[][] lists = new LinkedList<?>[n][n];
Or slightly more efficient in memory, just a single array:
LinkedList<?>[] lists = new LinkedList<?>[n * n];
// Then for access...
lists[y * n + x] = ...;
Then you'd need to cast on each access - using #SuppressWarnings given that you know it will always work (assuming you encapsulate it appropriately). I'd put that in a single place:
#SuppressWarnings("unchecked")
private LinkedList<Foo> getList(int x, int y) {
if (lists[y][x] == null) {
lists[y][x] = new LinkedList<Foo>();
}
// Cast won't actually have any effect at execution time. It's
// just to tell the compiler we know what we're doing.
return (LinkedList<Foo>) lists[y][x];
}
Of course in both cases you'd then need to populate the arrays with empty linked lists if you needed to. (If several of the linked lists never end up having any nodes, you may wish to consider only populating them lazily.)
I would certainly not generate a class with hundreds of variables. It would make programmatic access to the lists very painful, and basically be a bad idea in any number of ways.
Our class is learning about hash tables, and one of my study questions involves me creating a dictionary using a hash table with separate chaining. However, the catch is that we are not allowed to use Java's provided methods for creating hash tables. Rather, our lecture notes mention that separate chaining involves each cell in an array pointing to a linked list of entries.
Thus, my understanding is that I should create an array of size n (where n is prime), and insert an empty linked list into each position in the array. Then, I use my hash function to hash strings and insert them into the corresponding linked list in the proper array position. I created my hash function, and so far my Dictionary constructor takes in a size and creates an array of that size (actually, of size 4999, both prime and large as discussed in class). Am I on the right track here? Should I now insert a new linked list into each position and then work on insert/remove methods?
What you have sounds good so far.
Bear in mind that an array of object references has each cell null by default, and you can write your insert and remove functions to work with that. If you choose to create a linked list object that contains no data (sometimes called a sentinel node) it may be advantageous to create a single immutable (read-only) instance to put in every empty slot, rather than create 4,999 separate instances with new (where most don't hold any data).
It sounds like you are on the right track.
Some extra pointers:
It's not worth creating a LinkedList in each bucket until it is actually used. So you can leave the buckets as null until they are added to. Just remember to write your accessor functions to take account of this.
It's not always efficient to create a large array immediately. It can be better to start with a small array, keep track of the capacity used, and enlarge the array when necessary (which involves re-bucketing the values into the new array)
It's a good idea to make your class implement the whole of the Map<K,V> interface - just to get some practice implementing the other standard Java collection methods.
I am writing a program that will be heavily reliant on ... something ... that stores data like an array where I am able to access any point of the data at any given time as I can in an array.
I know that the java library has an Array class that I could use or I could use a raw array[].
I expect that using the Array type is a bit easier to code, but I expect that it is slightly less efficient as well.
My question is, which is better to use between these two, and is there a better way to accomplish the same result?
Actually Array would be of no help -- it's not what you think it is. The class java.util.ArrayList, on the other hand, is. In general, if you can program with collection classes like ArrayList, do so -- you'll more easily arrive at correct, flexible software that's easier to read, too. And that "if" applies almost all the time; raw arrays are something you use as a last resort or, more often, when a method you want to call requires one as an argument.
The Array class is used for Java reflection and is very, very, rarely used.
If you want to store data in an array, use plain old arrays, indicated with [], or as Gabe's comment on the question suggests, java.util.ArrayList. ArrayList is, as your comment suggests easier to code (when it comes to adding and removing elements!!) but yes, is slightly less efficient. For variable-size collections, ArrayList is all but required.
My question is, which is better to use between these two, and is there a better way to accomplish the same result?
It depends on what you are trying to achieve:
If the number of elements in the array is known ahead of time, then an array type is a good fit. If not, a List type is (at least) more convenient to use.
The List interface offers a number of methods such as contains, insert, remove and so on that can save you coding ... if you need to do that sort of thing.
If properly used, an array type will use less space. The difference is particularly significant for arrays of primitive types where using a List means that the elements need to be represented using wrapper types (e.g. byte becomes Byte).
The Array class is not useful in this context, and neither is the Arrays class. The choice is between ArrayList (or some other List implementation class) and primitive arrays.
In terms of ease of use, the Array class is a lot easier to code.
The array[] is quite a problem in terms of the case that you need to know
the size of the list of objects beforehand.
Instead, you could use a HashMap. It is very efficient in search as well as sorting as
the entire process is carried out in terms of key values.
You could declare a HashMap as:
HashMap<String, Object> map = new HashMap<String, Object>();
For the Object you can use your class, and for key use the value which needs to be unique.