Creating a list from size - java

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.

Related

How to create ArrayList without using add-function

As the title implies, I'd like to know how to insert different values into my ArrayList, without using too much space for several "add" functions.
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(3,4));
ArrayCheck.allDivisibleBy(arr, divisor);
I have got an arraylist called arr, and I don't know if this is the right way to add several values (3,4) that way.
Furthermore I would also like to check the values in another method called allDivisbleBy. The function of this method is not relevant though, but I want to check the values and am not sure if "ArrayCheck" is a way to send the array values to the method.
The simplest way is to use Arrays.asList(arr). As expected, that static method returns a List with as it's contents the elements of the array.
I don't know if this is the right way to add several values (3,4) that
way
Yes it is. Else you can use this:
ArrayList<Integer> arr = new ArrayList<Integer>(2);
arr.add(3);
arr.add(4);
I want to check the values and am not sure if "ArrayCheck" is a way to
send the array values to the method
ArrayCheck is not a standard java class.
Check all of your inputs for your condition, put them in a Collection and use method addAll instead of add to add all of collection items at once.

How to combine array with arraylist in 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

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);

How do I iterate over multiple lists in parallel in Java? [duplicate]

This question already has answers here:
How to most elegantly iterate through parallel collections?
(8 answers)
Closed 7 years ago.
I want to create a function to iterate over multiple lists. Now I know these lists have exactly the same size (and they can have different types too), for example:
List<Integer> list1 = getList1();
List<String> list2 = getList2();
List<Long> list3 = getList3();
list1.size() == list2.size(); // returns true
list2.size() == list3.size(); // returns true
And I want to be able to call a function which takes 3 elements at the same slice in each of these lists so for exemple:
int calculate(int elemList1, String elemList2, long elemList3) {...}
// iterator over the lists in parallel {
int ret = calculate(elemList1, elemList2, elemList3);
// }
I would like to do the equivalent of what I saw discussed in guava here but doesn't look implemented yet: http://code.google.com/p/guava-libraries/issues/detail?id=677
They talk about doing Iterators.interleave or Iterators.zip and I would like to do something similar but I haven't been able to, so can someone please help me a bit? Thanks!
I would prefer to not have to get the size of one list and iterate over them by index, because in the future i can have lists of different sizes so i would like to use only 1 way to do this.
A compound Iterator might be a cool idea, e.g.:
Iterator<Array<?>> compoundIterator = createIterator(List1, List2, List3);
Then inside the implementation, you would create iterators for each of the lists, then loop through the items and put them into an array, then your consumption of that stuff would look something like:
while (compoundIterator.hasElements()){
Array[] elements = compountIterator.nextElement();
calculate(elements[0], elements[1], elements[2]);
}
What's nice about this solution is you are hiding all those details about whether one list ran out or not (of course you have to decide what you want to do if one does, but that could be wrapped inside as well).
I don't think you are really saying in parallel, since the values are being used to invoke a method. If you want the same elements from each list, concurrently skipping through different lists on different threads does you no good.
You just need to do a for loop and then call list1.get(i), list2.get(i), list3.get(i).
You can create a new thread and iterate your list there. Spawn multiple of this therad and you can iterate your list in parallel.
If you want to pass List of any template type, you can just specify your method parameter as List, although this might result in compiler warnings. Other thing you can try is pass the list as List<T extends Object> and do a runtime check of type T and action accordingly
However if by 'parallel' you are not referring to multithreading / concurrency -- instead just want to be able to iterate your 3 lists in one single loop, then something like this will do (warning code is rough example only -- not tested / complying with coding standard):
List list1 = ...
List list2 = ...
List list3 = ...
for(int i=0,j=0,k=0; i<list1.size() && j<list2.size() && k<list3.size(); ++i,++j,++k)
{
Object elemOfList1 = list1.get(i);
Object elemOfList2 = list2.get(j);
Object elemOfList3 = list3.get(k);
// do something here
}

Java: How to initialize a fixed length List of List?

I have a list of String[] that contains some data returned from a database
List<String[]> x;
Now for each "x" I have to store its relative Ys. (Imagine that "x" contains the elements returned from a "SELECT DISTINCT xColumn1, xColumn2 FROM table" and now for each element I have to store the data from another query).
Y's elements are going to be stored here:
List<List<String[]>> yElements;
I've read that I can declare a fixed length list, but I don't know how. This is what I have done:
yElements = Arrays.asList(new List<String[]>[x.sixe()]);
Netbeans told me "generic array creation" error.
I also want to tell you that I MUST have a fixed lenght list to store a List of String[ ] in a specific index of this List of Lists. (If you can show me how to do with an array it would be great, too!)
Thanks.
If you want your lists to be absolutely fixed size, you could use the native arrays. They can be multi-dimensional so for example you can have String[][] x or `String[][][] y'.
Honestly however, your approach is a bit confusing and not that crisp from a design point of view.
Why not, similarly to as was suggested in the comment, have an object which has both columns (xColumn1, xColumn2), and then have the Y elements in a separate object, which can then be associated with the first one?
so:
class XDetails
{
String xColumn1;
String xColumn2;
YDetails relatedY;
...
}
class YDetails
{
... fields of Y ...
}
Then you can have an array or List<XDetails>
You cannot create an instance of an array of a generic type using new.
One alternative is this:
import java.lang.reflect.*;
import java.util.*;
public class Test
{
public static void main( String args[] )
{
List<String[]> x = ...;
List<List<String[]>> yElements = Arrays.asList(
(List<String[]>[])Array.newInstance(List.class, x.size()));
}
}
Related question: How to create a generic array in Java?. (The example there is about creating an instance of an array of a generic type parameter ... but the same approach applies here.)
However, I think that this whole question is based on an incorrect assumption.
I also want to tell you that I MUST have a fixed lenght list to store a List of String[ ] in a specific index of this List of Lists.
You don't HAVE TO have a fixed sized list. From the computational perspective, your code would work just fine with a non-fixed sized list ... provided that you don't add or remove list elements. (In fact, using Arrays.asList to wrap an array won't stop some other code trying to add / remove elements ...) Anyway ... if you just make the implementation type ArrayList<ArrayList<ArrayList<String>>>, then the generic array creation problem goes away.
In addition, I suspect that it is incorrect to use x.size() as the size of yElements. The size of yElements probably should be determined by the number of x instances there are going to be, not the size of a given x instance.

Categories