I know that it's possible to create a 2D ArrayList with ArrayList<ArrayList<E>>, but that is cumbersome and a real casting nightmare when it comes to adding and retrieving objects.
Are there any 2D ArrayList classes that do this sort of thing more efficiently? I am writing a true 2D ArrayList class from the ground up, and I'm wondering if there is anyone else who has done this sort of thing in an efficient manner.
no, unfortunately there isn't 2d ArrayList class. your alternative options are (in case 0/1/2 of the Diamension is constant):
MyType[][] myList = new MyType[n][m];
or
ArrayList<MyType>[] myList = new ArrayList<MyType>[n];
or
ArrayList<ArrayList<MyType>> myList = new ArrayList<ArrayList<MyType>>();
another option is to save all your data in 1d ArrayList and create a function that recieve (x,y) and return the place x in the ArrayList. this way you demonstrate outside a 2d array, but save the elements easily in 1d ArrayList
Using the "ArrayList>" type approach is fine and pretty standard for this kind of thing from what I have seen. You can easily write a 2D array list class that provides convenience methods for adding / removing items, etc, and it will be far from "cumbersome" or "a casting nightmare" to use this. Have a look at this implementation as an example. It is not quite perfect but it illustrates how easy it is to use this kind of approach.
Have a look at FastTable in javolution and Table implementations in guava
Google Collections has a Table collection. It's laid out as Rows/Cols and accesible directly, bycol, and by rows. Different implementations of Table have different efficiencies based on access type
I built a 3D "grid" data structure, if it is any help.
https://github.com/mikera/mikera/blob/master/src/main/java/mikera/engine/TreeGrid.java
The key trick is sub-dividing space into "blocks" so that sparse data can be efficiently stored.
You can use it as a 2D collection if you like by ignoring the z dimension (keeping it at 0), though that is probably a bit of overkill. Still, an option if you want this kind of structure. Alternatively, you could simplify it down to 2D.
Related
What is the difference between using a Guava Table implementation and a 2D array if I know the size of the array beforehand?
Is one more efficient than the other? How?
Would it make a difference in running time?
The most obvious and crucial difference is that an array is always indexed, with ints, whereas a Table can be indexed with arbitrary objects.
Consider the Table Example from the Guava site:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
...
The indexing here happens via Vertex objects. If you wanted to do the same with an array, you would have to add some getIndex method to the Vertex class, and accesss the array like this
double array[][] = new double[4][5];
array[v1.getIndex()][v2.getIndex()] = 4;
This is inconvenient and particularly hard to maintain - especially, when the indices may change (or when vertices have to be added/removed, although you mentioned that this is not the case for you).
Additionally, the Guava table allows obtaining rows or columns as separate entities. In a 2D array, you can always access either one row or one column of the array - depending on how you interpret the 2 dimensions of the array. The table allows accessing both, each in form of a Map.
Concerning the performance: There will be cases where you'll have a noticable difference in performance. Particularly when you have a large 2D array of primitive types (int, double etc), and the alternative would be a large table with the corresponding reference types (Integer, Double etc). But again, this will only be noticable when the array/table is really large.
Additionally to what Marco13 said, read this: https://stackoverflow.com/a/6105705/1273080.
Collections are better than object arrays in basically every way
imaginable.
The same applies here. A 2D array is a low-level tool that might be needed when you need some high-performance structure for primitives. However, arrays have no meaningful methods, no behaviour, no nothing, and therefore are usually an underlying data structure in classes that add some behaviour to them. Do this with a 2D fixed-size array and you'll end up with ... a Guava-esque Table.
Also, a Table can be a 2D-array, or a Map<R, Map<C, V>>, in the future we might also have resizable Table implementations - all within one interface.
Regarding the performance - you should almost always go for the more high-level approach to get code as readable and clear as possible, then measure the performance and only if it's problematic, go for different approaches.
I am new to java.
I am creating a school project in which I am using arrays.
My question is:
what is better - if i sort an array it also takes time in sorting.So will it be good to leave it unsorted for my small school project and while retrieving i will put some logic to retrive the desired array value.
It's better to keep it sorted if you think you will need sorted values at some later stage.
It would be better if you would paste your code here.
Either you sorted or not it is necessary to apply a logic to retrieve values from an array. If your array not a very large one you may not want to bother about performance since sorting doesn't take much time for smaller arrays.
It is better to use List over arrays since it has an implementation called ArrayList which grows dynamically.
If it is possible, may be is better use a vector
Have you think what would happen when you insert a new item in your array? Or if you change the way of sorting? If you keep the array sorted, keep in mind this things.
For these reasons, I think is better to sort the array each time you need to return a value (the best is using Vectors, as I said at the beginning).
I have a document with 15,000 items. Each item contains 6 variables (strings and integers). I have to copy all of these into some sort of two dimensional array, what the best way to do it?
Here are my ideas so far:
Make a GIANT 2D array or array list the same way you make any other array.
Pros: Simple Cons: Messy(would create a class just for this), huge amount of code, if I make a mistake it will be imposable to find where it is, all variables would have to be string even the ints which will make my job harder down the road
Make a new class with a super that takes in all the variables I need.
Create each item as a new instance of this class.
Add all of the instances to a 2D array or array list.
Pros: Simple, less messy, easier to find a mistake, not all the variables need to be strings which makes it much easier later when I don't have to convert string to int, a little less typing for me Cons: Slower? Will instances make my array compile slower? And will they make the over all array slow when I'm searching to items in it?
These ideas don't seem all to great :( and before I start the three week, five hour a day process of adding these items I would like to find the best way so I won't have to do it again... Suggestions on my current ideas or any new ideas?
Data example:
0: 100, west, sports, 10.89, MA, united
*not actual data
Your second options seems to be good. You can create a class containing all the items and create an array of that class.
You may use the following:
1. Read the document using buffered reader, so that memory issues will not occur.
2. Create a class containing your items.
3. Create a List of type you need and store the elements into it.
Let me know in case you face further problems.
If you already have the document with the 15000 * 6 items, in my experience you would be better served writing a program to use regex and parse it and have the output be the contents of the java array in the format you want. With such a parsing program in place, it will then also be very easy for you to change the format of the 15000 lines if you want to generate it differently.
As to the final format, I would have an ArrayList of your bean. By you text thus far, you don't necessarily need a super that takes in the variables, unless you need to have subtypes that are differentiated.
You'll probably run out of static space in a single class. So what I do is break up a big class like that into a file with a bunch of inner nested classes that each have a 64K (or less) part of the data as static final arrays, and then I merge them together in the main class in that file.
I have this in a class of many names to fix:
class FixName{
static String[][] testStrings;
static int add(String[][] aTestStrings, int lastIndex){
for(int i=0; i<aTestStrings.length; ++i) {
testStrings[++lastIndex]=aTestStrings[i];
}
return lastIndex;
}
static {
testStrings = new String[
FixName1.testStrings.length
+FixName2.testStrings.length
+FixName3.testStrings.length
+FixName4.testStrings.length
/**/ ][];
int lastIndex=-1;
lastIndex=add(FixName1.testStrings,lastIndex);
lastIndex=add(FixName2.testStrings,lastIndex);
lastIndex=add(FixName3.testStrings,lastIndex);
lastIndex=add(FixName4.testStrings,lastIndex);
/**/ }
}
class FixName1 {
static String[][] testStrings = {
{"key1","name1","other1"},
{"key2","name2","other2"},
//...
{"keyN","nameN","otherN"}
};
}
Create a wrapper (Item) if you have not already(as your question does not state it clearly).
If the size of the elements is fixed ie 1500 use array other wise use LinkedList(write your own linked list or use Collection).
If there are others operations that you need to support on this collection of items, may be further inserts, search( in particular) use balanced binary search tree.
With the understanding of the question i would say linked list is better option.
If the items have a unique property (name or id or row number or any other unique identifier) I recommend using a HashMap with a wrapper around the item. If you are going to do any kind of lookup on your data (find item with id x and do operation y) this is the fastest option and is also very clean, it just requires a wrapper and you can use a datastructure that is already implemented.
If you are not doing any lookups and need to process the items en masse in no specific order I would recommend an ArrayList, it is very optimized as it is the most commonly used collection in java. You would still need the wrapper to keep things clean and a list is far cleaner than an array at almost no extra cost.
Little point in making your own collection as your needs are not extremely specific, just use one that is already implemented and never worry about your code breaking, if it does it is oracles fault ;)
I want to use data structure that needs to be sorted every now and again. The size of the data structure will hardly exceed 1000 items.
Which one is better - ArrayList or LinkedList?
Which sorting algorithm is better to use?
Up to Java 7, it made no difference because Collections.sort would dump the content of the list into an array.
With Java 8, using an ArrayList should be slightly faster because Collections.sort will call List.sort and ArrayList has a specialised version that sorts the backing array directly, saving a copy.
So bottom line is ArrayList is better as it gives a similar or better performance depending on the version of Java.
If you're going to be using java.util.Collections.sort(List) then it really doesn't matter.
If the List does not implement RandomAccess, then it will be dumped to a List The list will get dumped into an array for purposes of sorting anyway.
(Thanks for keeping me honest Ralph. Looks like I confused the implementations of sort and shuffle. They're close enough to the same thing right?)
If you can use the Apache library, then have a look at TreeList. It addresses your problem correctly.
Only 1000 items? Why do you care?
I usually always use ArrayList unless I have specific need to do otherwise.
Have a look at the source code. I think sorting is based on arrays anyway, if I remember correctly.
If you are just sorting and not dynamically updating your sorted list, then either is fine and an array will be more memory efficient. Linked lists are really better if you want to maintain a sorted list. Inserting an object is fast into the middle of a linked list, but slow into an array.
Arrays are better if you want to find an object in the middle. With an array, you can do a binary sort and find if a member is in the list in O(logN) time. With a linked list, you need to walk the entire list which is very slow.
I guess which is better for your application depends on what you want to do with the list after it is sorted.
I've been thinking about this one for a long time. What is the difference between Vectors and Arrays? I know they do similar things, if not exact.
String Array
String[] array = new String[4];
String Vector
Vector<String> vector = new Vector<String>(4);
It seems kind of redundant to me why there would be both arrays and vectors. Are there any advantages or disadvantages to using one or the other?
Vectors are resizable. Arrays are not.
The difference is that 'Vector' is an extension by programmers, whereas an array is a built-in function of the language itself.
You can edit how the Vector behaves (by editing its source code), whereas an array is defined by the compiler.
And obviously, Vectors can be potentially sized (depending on implementation). Arrays are static and cannot be resized - you have to recreate it and copy the data over.
Vector is synchronized. Arrays are not(?).
Array cannot be re-sized, while Vectors can.
Vector uses Arrays internally. The main advantage of a Vector compared to an Array is its automatical increase of capacity. An Array keeps its size once created, a Vector does not
It seems kind of redundant to me why there would be both arrays and
vectors
For one, Vectors can be resized. If you declare an array of size 10, you are left with 10 always, unless you copy the contents to another larger sized array. Methods of Vector are synchronized.
Vectors are part of the collections framework. Vector is a List. There are other lists, ArrayLists, LinkedLists etc with specific features. There are Sets and Maps. All of them hold "lists" of items, but each of them give specific advantages in specific situations.
You might want to read about java collections.
Vectors will automatically resize for you to accommodate as many entries as you want in them. An array is fixed in size, and will give you an OutOfBounds exception when you try to add more than you allocated.
When you provide the size for a vector, that's just the original size it starts with. It'll automatically grow/shrink as necessary.
1- Vectors are resize-able, arrays are not
2- Vectors are responsible for memory allocate and release, arrays are not. This makes vectors safer to use than arrays.
3- Vectors have a good performance on their implemented functions, which you may not reach by your own programming with arrays.
4- Finally I think it's wiser to use vectors, most of the times.
An array is a basic java data structure, whose size is fixed when defined.
A Vector is part of the Java Collections Framework, and contrary to your beliefs, or not even close to the same thing as an array. Among many other things, Vectors are resizable and can interact with other collections.
Java array types are not necessary. They actually create a lot of problems. Avoid them if you can.
We could do better to replace them with a standard class Array<T>. Some new post-Java languages are taking this approach.
(History alert) In the old days, Java didn't have generics, a non-generic collection class would suck to use (with lots of castings). Then array types were really poor man's generics because they carry element type info. That's why many methods return arrays, instead of List.
I think the above suggestion is not good. Check this link to get brief idea.
Difference b/w Array and Vector
Vectors help to insert and delete elements easily while arrays helps to sort and access elements with ease.
Vectors can hold different type of elements
Arrays only the type defined when forming them
You can use array list which is some what similar to vector and provided much better features