Multi-Dimensional Container in Java - java

I searched around on Google, but I was unable to find any libraries for a multi-dimensional container in Java (preferably one that supports generics as well). I could easily write one (in fact, I have started to), but I was hoping that I would be able to reuse the work someone else has done for the sake of efficiency. I don't necessarily need to provide any sort of additional functionality outside of the "container" realm (AKA, no matrix functionality for example).
Does anybody know of any type of class/library for a multi-dimensional container? Thanks!
Edit: To clarify, yes, I am looking for a Collection of Collections of Collections ... (or int[][][][][], etc). Essentially, a multi-dimensional array.

Something like this, a Collection of Collections?
Collection<Collection<Object>> multiDimensional =
new ArrayList<Collection<Object>>();
Or something completely different?

Google Collections supports multimaps and multisets (bags). Is that what you mean?

Can't you use a jagged array (eg int[][])?
You can make it n-dimensional (int[][][][]), but it starts to get silly after a while

Related

Raw arrays vs collections

I have gone through many codebases on Github and almost everywhere I found one common pattern to use Arrays instead of Lists.
example :
Class Attributes {
...
...
Attribute[] attribute;
...
...
}
So My question here is, Why do most of these projects are using raw arrays and not collections?
The below code is still the same functionality wise and using arrays require most of the code to be re-written to handle expansion of array.
Class Attributes {
...
...
List<Attribute> attribute;
...
...
}
EDIT 1: After a lot of searching I found out that arrays have lower memory footprint than Collections. So now the question arises, Why is this?
Well, the obvious answer seems because internally they use a lot of other variables to maintain the state and do a lot of other stuff.
But isn't that required anyway, I mean if we want to store numbers and the size of array can increase or decrease decrease, we'll have to implement those methods anyway.
I don't know your sources, but I'm pretty sure collections are used more often than arrays, since they provide a dynamic structure. Yet there are good reasons to use arrays as well;
-If you have limited memory, using arrays is a better choice.
-If you have strict deadlines on your program, using arrays is a better choice.
-If you know the amount of elements to use in your program, using arrays is a better choice.
In a nutshell, if you need performance, or you have limited resources use arrays. If you need functionality, use collections.

Does PHP have Different Implementations of Lists

I'm more of a java guy, and I was talking with a PHP guy. He said that PHP pretty much only uses arrays for lists. Googling for different concrete implementations of lists in PHP was unfruitful for me.
Being that there are different advantages of concrete implementations of lists in java, I found this hard to believe that there wasn't something similar in PHP.
Is there PHP equivalents of the following: Singly Linked List, ArrayList (yes, the array of course), Vector, and Stack?
As mentioned above the basic PHP datatypes most people would use Array as Java lists, consider the available types that most PHP developers know of
http://php.net/manual/en/language.types.php
Array is the one that mostly does what you want. However the Standard PHP Libary (SPL) do have some data-structures that might interest you, mostly the SplDoublyLinkedList.
You might also want to note that it provides SplFixedArray to handle the issue PHP can have when you work with arrays (PHP have many adventages memory use is not one of them, see https://nikic.github.io/2011/12/12/How-big-are-PHP-arrays-really-Hint-BIG.html)

Array vs ArrayList: Dynamic Use

Both ArrayLists and Vectors make use of typical arrays internally. However, that leaves me thinking... why would I use ArrayLists when I can technically do the same thing using Arrays? Is convenience the only reason? Do performance-critical applications ever make use of an ArrayList?
Any tips would be appreciated.
I believe there are multiple reasons to prefer Lists over "implementing lists over arrays" or over "using arrays", but here are the two that I think are most important:
Lists have better support to generics than Arrays (you can, and should, read about it in "Effective Java" by Bloch - see Item 25)
If you ask about using ArrayList vs. implementing it yourself - I find it hard to believe that you'll do a better job than the guys that developed it in openjdk (Josh Bloch and Neal Gafter).
Yes, performance critical applications use ArrayList all the time. It's very unlikely that array access is the dominant factor in the vast majority of programs written in Java.
The ArrayList Collection interface is much richer than the functionality provided by built-in primitive arrays. This extra functionality will save you development time as well as debugging time by not having to write those algorithms yourself.
Additionally, many programmers are already familiar with the ArrayList Collection interface and thus by utilizing the existing standard libraries it will make your code easier to read and maintain for the long term.
One reason is that ArrayLists sizes are dynamic, arrays aren't.
The internal implementation of ArrayList is array only. but ArrayList is an wrapper class which is having more capabilities added to it. These capabilities are not available when you deal with Array directly.
For example,
Delete an element from array, you will have to implement logic if your are using an Array. But if you are using ArrayList, it will do the deletion for you.
Adding an element to array:
If you are using an array, you will have to implement the logic. But using an ArrayList, it is pretty easy.
You will find lot of methods in this ArrayList class that are handy for day to day use.
Hope this will help you.

Google Collections equivalent to Apache Commons Collections ArrayUtils.toObject and ArrayUtils.toPrimitive

Since everyone praises Google Collections (e.g. in here)
How come I can't find the equivalent of ArrayUtils.toObject() and ArrayUtils.toPrimitive()? is it that unusable? did I miss it?
To be honest I'm not sure if either of those methods should even qualify as a collection-related operation and as such I'd wonder why they're even there in the first place.
To clarify a bit, collections are generically a group of objects with some semantic data binding them together while arrays are just a predetermined set of something. This semantic data may be information about accepting or rejecting nulls, duplicates, objects of wrong types or with unacceptable field values etc.
Most -if not all- collections do use arrays internally, however array itself isn't a collection. To qualify as a collection it needs some relevant magic such as removing and adding objects to arbitrary positions and arrays can't do that. I very much doubt you'll ever see any kind of array support in Google Collections since arrays are not collections.
However since Google Collections is going to be part of Google's Guava libraries which is a general purpose utility class library/framework of sorts, you may find what you want from com.google.common.primitives package, for example Booleans#asList(boolean... backingArray) and Booleans#toArray(Collection<Boolean> collection).
If you absolutely feel they should include equal methods to Apache Commons Collection's .toObject() and .toPrimitive() in there, you can always submit a feature request as new issue.

Java-like Collections in PHP

I'm learning PHP5 (last time I checked PHP was in PHP4 days) and I'm glad to see that PHP5 OO is more Java-alike than the PHP4 one but there's still an issue that makes me feel quite unconfortable because of my Java background : ARRAYS.
I'm reading "Proffesional PHP6" (Wrox) and It shows its own Collection implementation.
I've found other clases like the one in http://aheimlich.dreamhosters.com/generic-collections/Collection.phps based on SPL.
I've also found that there's some kind of Collection in SPL (ArrayObject)
However, I'm surprised because I don't really see people using Collections in PHP, they seem to prefer arrays.
So, isn't it a good idea using Collections in PHP just like people use ArrayList instead of basic arrays in Java? After all, php arrays aren't really like java arrays.
Collections in Java make a lot of sense since it's a strongly typed language. It makes sense to have a collection of say "Cars" and another of "Motorbikes".
However, in PHP, due to the dynamically typed nature, it is quite common to sacrifice the formality of Collections. Arrays are sufficient to be used as generic containers of various object types (Cars, Motorbikes, etc.). Also, the added benefit comes from the fact that arrays can be mutated very easily (which sometimes can be a big disadvantage when proper error checking is absent).
I come from a Java background, and I've found that using a Collections design pattern in PHP does not buy much in the way of advantages (no multi-threading, no optimization of memory allocation, no iterators, etc.).
If you're looking for any of those advantages, its probably better to construct a wrapper class around the array, implementing each feature (iterators, etc.) a la carte.
I am very pro collection objects in PHP, they can be used to add type safety, impliment easy to use search, sort and manipulation functionality, and represent the correct OO approach rather then using arrays and the multitude of useful but procedual functions that operate on them in differing patterns all over the source.
We have various collections that we use for various purposes all neatly inherited promoting type safety, consistent coding standards and a high level of code reuse.
But ultimatley, they are all array's internally!
I suppose really it comes down to choice, but in my object oriented world I like to keep easily repeatable segments of code such as sort and search algorithms in base classes, and I find the object notation more self documenting.
PHP arrays are associative... They're far more powerful than Java's arrays, and include much of the functionality of List<> and Map<>.
What do you mean by "good idea"? They're different tools, using one language in the way you used another usually results in frustration.
I, too, was somewhat dismayed to find no Collection type classes in PHP. Arrays have a couple of real disadvantages in my experience.
First, the number of functions available to manipulate them is somewhat limited. For example, I need to be able to arbitrarily insert and remove items to/from a Collection at a given index position. Doing that with the built-in language functions for arrays in PHP is painful at best.
Second, as a sort of offshoot of the first point, writing clean, readable code that manipulates arrays at any level of complexity beyond simple push/pop and iterator stuff is difficult at best. I often find that I have to use one array to index and keep track of another array in data-intensive apps I create.
I prefer working in a framework (my personal choice is NOLOH). There, I have a real Collection class called ArrayList that has functions such as Add, Insert, RemoveAt, RemoveRange and Toggle. I imagine other PHP frameworks address this issue as well.
A nice implementation of collection in php is provided by Varien Lib, this library is part of Magento code with OSL license. ( more info about Magento license and code reuse here.
Cannot find any source code for the library so the best way is to download magento and then look in /lib/Varien/
Yii has implementation of full java like collections stack
http://www.yiiframework.com/doc/api/1.1/CList
I sometimes use this really simple implementation to give me a rough and ready collection.
Normally the main requirement of a collection is enforcing a group of one type of object, you just have to setup a basic class with a constructor to implement it.
class SomeObjectCollection {
/**
* #var SomeObject[]
*/
private $collection = array();
/**
* #param SomeObject $object1
* #param SomeObject $_ [optional]
*/
function __construct(SomeObject $object1 = null, SomeObject $_ = null)
{
foreach (func_get_args() as $index => $arg) {
if(! $arg instanceof SomeObject) throw new \RuntimeException('All arguments must be of type SomeObject');
$this->collection[] = $arg;
}
}
/**
* #return SomeObject[]
*/
public function getAll()
{
return $this->collection;
}
}

Categories