How to combine array with arraylist in Java? - java

I need a 5-dimensional data structure in Java with "double" as type for all the cells. For 3 of dimensions I know the size, so it fits to array category. But for 2 of dimensions I don't know the size beforehand; looks like ArrayList.
I have been able to manage the combination for 3 dimensions in the past:
ArrayList(Double)[][] prXifY = (ArrayList(Double)[][]) new ArrayList[m][n];
But despite long hours working on it (and through search in the net), I wasn't able to scale it. I need something like this:
ArrayList(ArrayList(Double))[][][] prXiXjY = (ArrayList(ArrayList(Double))[][][]) new ArrayList(ArrayList<Double))[m][m][n];
When I tried the above code, it says:
"Cannot create a generic array of ArrayList(ArrayList(Double))"
I will appreciate quick and complete answers.
By the way, this is my very first post ever. I tried my best to do a good job on searching beforehand and explaining the problem clearly. Comments on these matters are appreciated as well. :)

An ArrayList is an object, and instantiated differently than an array is. In general, to say that you want an ArrayList that holds doubles, you might use something like:
ArrayList<Double> list = new ArrayList<Double>();
to specify that you have an ArrayList which holsts ArrayLists which hold doubles...
ArrayList<ArrayList<Double>> list = new ArrayList<ArrayList<Double>>();
You see where this is going, I hope.
This just creates the top-level list - it doesn't create any of the cells themselves. For that, you'll need additional new statements. This is going to get messy fast, and you may want to stop and consider if there is a better way to store the data than in a 5-dimension array.

I think what you want would look something like this
List<List<List<List<List<Double>>>>> myList= new ArrayList<List<List<List<List<Double>>>>> ();
as you can tell this looks insane and will be very hard to maintain. You should probably look at alternative methods of doing this.

Multi dimensional arrays can be created like so:
ArrayList<Double> oneDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<Double>> twoDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<Double>>> threeDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<Double>>>> fourDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Double>>>>> fiveDimensionalArrayList = new ArrayList<>();
But I would definitely recommend considering whether a 5 dimensional array is what you require for the problem at hand; it smells like something is wrong

Related

How can I add an Array into a Queue?

Is it possible to add an array into specifically, a ConcurrentLinkedQueue? If so, how exactly would the .add statement look like?
THIS IS HOMEWORK RELATED, however, my entire program is meant to perform calculations on MyObjects (the default constructor of MyObjects generates random values to perform a ton of calculations on).
For example:
//Note: I couldn't use the Diamond Braces for the Queue-type when posing this question
ConcurrentLinkedQueue theLinkedQueue {MyObjects[]} =
new ConcurrentLinkedQueue{MyObjects[]}();
MyObjects[] theArray = null;
for(int i = 0; i < 100; i++){
theArray = new MyObjects[CONSTANT_SIZE];
theLinkedQueue.add(theArray(objparameter1, objparameter2));
}
The program implements multi-threading and in my thread class I've passed the Queue into the constructor, and am attempting to take off a MyObject array which a MyObject temp will point to, but so far I'm only capable of adding a single MyObject to my Queue at a time and pulling it. I want to be able to add the same amount of MyObjects as individual components rather than individually. I've attempted various lines of code only for NetBeans IDE to recommend a method to throw an UnsupportedOperation Exception. How could I add arrays into my ConcurrentLinkedQueue?
(Also apologies if my question is dense or confusing, first time posting here).
The correct syntax for the declaration of your queue is:
ConcurrentLinkedQueue<MyObjects> theLinkedQueue = new ConcurrentLinkedQueue<>();
Start with that and see how things go from there.
I figured out the solution, which was simply to add the array without 'objparameters' included.
theLinkedQueue.add(a); //where a was a 'MyObject' array.
I presumed you had to load the parameter to be passed for each array index, which seems pretty silly.

List of list iteration in code below -- which is better approach?

I am iterating over a List of Lists. In my code listofuserdetailsperAccount is List<List>. I am considering the two methods below, please let me know which way is correct, more efficient and should be followed in java coding.
Way 1-----
for(int i=0;i<=listofuserdetailsperAccount.size();i++){
List list=(List) listofuserdetailsperAccount.get(0);
}
Way 2---
for(int i=0;i<=listofuserdetailsperAccount.size();i++){
List list= new ArrayList();
list=(List) listofuserdetailsperAccount.get(0);
}
I'll go with for each loop
for( List userDetailsPerAccount : listOfUserDetailsPerAccount ) {
//anything you want to do with userDetailsPerAccount
}
Way 1 is better approach than Way 2. In Way 2 List list= new ArrayList(); it will create a extra ArrayList object which does not have any use, which will cause memory consumption for sometime.
And it is also recommended use type specific List<E> so that you dont cast at runtime it will be typesafe.
for(List<E> list : listOfUserDetailsPerAccount){
...
}
In Java 5 and above use for-each.
You have a couple of problems here, with both proposed solutions.
Your List<List> listofuserdetailsperAccount object is not properly typed, as the inner List is a raw type, something to be avoided. Assuming your inner list holds UserDetail objects, your list of lists should be of type List<List<UserDetail>>.
You don't use the for-each loop syntax to iterate over a List, which is Iterable.
for(List<UserDetail> innerList : listofuserdetailsperAccount)
In Way 2 you initialize List to a new ArrayList (which is a raw type, it should be new ArrayList<>() if you needed this) and then promptly overwrite this value with the contents of your outer list. This means you ask Java to construct a new object that is then immediately cleaned up by the garbage collector, unused. This is wasteful and unnecessary.
In summary, you likely want to do:
List<List<UserDetail>> listofuserdetailsperAccount = // initialize your list
for(List<userDetail> innerList : listofuserdetailsperAccount) {
// do work with your innerList now
}
You commented (tidied up):
So while initializing I am doing something like this now, can you please let me know if this is correct:
List<List<String>> listofAccountdetailsLoggedinUser = null;
listofAccountdetailsLoggedinUser = new ArrayList<List<String>>();
OR I should not put it as null and directly create an object like this:
List<List<String>> listofAccountdetailsLoggedinUser =
new ArrayList<List<String>>();
That is the right track, but you do not need to initialize the variable to null. It doesn't hurt anything, since it doesn't construct an unnecessary object, but there's no reason to - you can declare and initialize the variable in one line, like you do in your second example.
Additionally, you don't need to specify the type of the ArrayList on the right hand side, simply use the diamond operator <>, like so:
List<List<String>> listofAccountdetailsLoggedinUser = new ArrayList<>();
Also, consider a shorter variable name, there's no need to use such a long one, and it's no fun to type :)

how to achieve this in java ? requirement given below

I want to create a list of list
List<integer> nodes[10]=new ArrayList();
i want this, coz i will be iterating through it and reading data..and it will be dynamically created in runtime depending upon the size of inputs
Creating an array of List seems a little weird to me, not that you can't do it, it just seems counter intuitive to me...
Instead, I'd create a List of Lists, something like...
List<List<Integer>> nodes = new ArrayList<List<Integer>>(10);
You would then just need to populate them with actually values, this will depend on what you are doing, but something like...
nodes.add(new ArrayList<Integer>(10));
When you need to access a particular list/node, you would just access it like any normal List
List<Integer> listOfIntegers = nodes.get(0);
Take a look at the Collections tutorial and List JavaDocs and ArrayList JavaDocs for more details.
An array of ArrayLists
List<Integer>[] nodes = new ArrayList[count];
An ArrayList of ArrayLists
List<List<Integer>> nodes = new ArrayList<List<Integer>>(count);

Having trouble understanding how to create an array of linkedlists

Ok, so I have been reading every google result about creating an array of linkedlist, and most of the stack overflow threads, but I don't really understand what they are doing. Do I need to create a seperate class that extends linkedlist and then create an array of that class?
I have tried a million different ways of arranging this code, but this is what I have at the moment.
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
LinkedList<Integer>[] elementsLeftList = new LinkedList<Integer>[numElements];
The error is generic array creation. Can someone explain to me what is actually going on here.
In addition to the solutions below I was told you can create an array of head pointers.
Thanks in advance.
It's not allowed to create generic arrays, do the following
#SuppressWarnings("unchecked")
LinkedList<Integer>[] elementsLeftList = new LinkedList[numElements];
it works OK
You can't currently create an array of generics in Java without going through a complicated process. Can you do the following instead?
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
If you really need it as an array you can then get it from elementsLeftList.toArray() and cast the result.
You can read the following link for the explanation: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104

Creating a list from size

I know this is easy and can be done with 2 lines of code, but i am curious to know if there exists any such function
i have a int which tell me the size of list and i need to create a list say
List<Integer> intList;
i can create this by easily iterating through the size something like
for(int i=1 ; i <= size; i++) // started with 1 as i want it from 1
{
fill list
}
but i was just thinking as if there exists any such methods either in Collection API or Apache common
where i can pass the size to get a List with given size
Edit
May i was not able to put question in proper way, i want to get filled my list say
if size=4 than i was thinking abt something
Integer=1
Integer=2
Integer=3
Integer=4
and not an empty list with size 4
i know question do not make much sense, but still its better to clear your questions
Short answer: No
The two-liner you're currently using is already optimal.
The thing here is that List is an interface class and you can't create instances of an interface class. So before you want to construct it you need to know what kind of List you want to create. For the moment let's assume you want an ArrayList. From this moment on you can simply use the correct constructor to initialize your list e.g.
List<Integer> intList = new ArrayList<Integer>(10);
Which constructs an ArrayList of initial capacity 10.
For other kinds of list you can check the Java documentation.
To fill the list with initial data you can do something like this:
int[] myArray = new int[]{ 58,63,67,72,70,63,62,63 };
List<Integer> intList = new ArrayList<Integer>(myArray );
To answer the question after what you've added with your edit: No, there's no such method to fill a list with ascending integers in the standard collections API. You'll have to program a loop yourself and add elements to the list.

Categories