how to add a matrix to an ArrayList in java - java

I need to add a number of matrces to an arraylist or some sort of collection in order to recall them at a later stage
I have tried the arraylist and arraycopy
List<Double> al = new ArrayList<>();
double [][] k = new double [d.length][d[0].length];
System.arraycopy (d,0,k,0,d.length);
for (int i1 =0; i1 < d.length; i1++)
k[i1] = k.add(D[i1]);
al.add(k[i1]);
for (Integer x : k)
System.out.print(x + " ");
print2D(k);
I need an array of say 4x4 matrices
If I do say al.add(d); I get error: cannot find suitable method to add double
even when al.add(Matrix)

You forgot the array as type for your generics. What you want is List<double[][]> and not List<Double>. Then you will be able to add your matrices to the list.
The addition is simple, just
list.add(matrix);
// or in your case:
al.add(k);
no need to copy anything around or access the individual entries in the matrices.
You can retrieve matrices via get for example:
double[][] firstMatrix = list.get(0);

The list must be a list of matrices, and you are declaring a list of Doubles. Try something like this:
List<double[][]> list = new ArrayList<>();
double[][] matrix = {{1D,1D},{2D,2D}};
list.add(matrix);
Hope that helps!

Related

Best Way to create Adjacency List in java?

In general, to create Adjacency list of n node in java, we need to create an extra loop to fill the list with empty list like below-
for(int i=0;i<n;i++)
adj.add(new ArrayList<>());
Now we had to had to add the elements,but because of this extra loop its wasting the time.
Is there any other best way to create the adjacency list??????
If I need to make a compact representation of a graph, and I can get the neighbors for each vertex in sequence, I often do it like this:
//Concatenated adjacency lists for each vertex in order
ArrayList<Integer> adjList = new ArrayList<>();
//For each vertex, the end of its adjacency list in adjList
ArrayList<Integer> adjListEnds = new ArrayList<>();
for (int i=0; i<num_vertexes; ++i) {
for (int adj : getNeighbors(i)) {
adjList.add(adj);
}
adjListEnds.add(adjList.size());
}
Now, to get the neighbors of any vertex:
int s = vertex>0 ? adjListEnds.get(vertex-1) : 0;
int e = adjListEnds.get(vertex);
for (int i = s; i<e; ++i) {
processNeighbor(vertext, adjList.get(i));
}
Of course, if you want it to be really compact, then you should use something like an array list that holds primitive ints instead of Integers. Sometimes I roll my own. Sometimes I use gnu trove.

wanted put array list items into variables using loop

i am dynamically adding items to array-list after i wanted to
Initialize Variables using this array-list items
my array-list is
ArrayList<String> dayCountList = new ArrayList<String>();
i try to do like this but it doesn't work
for (int i = 0; i < dayCountList.size() ;i++) {
double day+"i" = Double.parseDouble(dayCountList.get(i));
}
You can create a array or array list of double type like this.
ArrayList<String> dayCountList = new ArrayList<String>();
.
.
double day[]=new double[dayCountList.size()];
// now use your loop like this
for (int i = 0; i < dayCountList.size() ; i++) {
day[i] = Double.parseDouble(dayCountList.get(i));
}
Now you can call your variables like day[0], for first element
day[1] ,for second and so on.
Hope this helped you.
If you are doing this, then you probably did not understand the purpose of array lists is. One purpose of array list is exactly to avoid creating a whole bunch of variables named day1, day2, day3 and so on.
You seem like you want to transform every element in the array list to a doubles. Why not create another ArrayList<Double> or double[] to store the transformed elements? Instead of writing day1, day2, you can say days.get(0), days.get(1) in the case of array lists. With arrays, you can do days[0], days[1] and so on.
ArrayList<Double> days = dayCountList.stream()
.mapToDouble(Double::parseDouble)
.boxed()
.collect(Collectors.toList());
// or
double[] days = dayCountList.stream()
.mapToDouble(Double::parseDouble).toArray()

Set size/dimensions of ArrayList<ArrayList<String>>

The problem
I have an ArrayList of ArrayLists. I am copying one over to the other, except in a different order (a rotation of the elements by 180°, but that's not important).
I have this generic code:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 5; c++) {
list.get(r).set(c, "an element from the other list");
}
}
I'm arbitrarily using sizes 4 for the number of rows and 5 for the number of columns.
However, this throws an index out of bounds error, obviously because I have no dimensions for the ArrayList<ArrayList<String>>.
I know that when creating an ArrayList, you can give it an initial capacity for a constructor parameter. However, I don't know how to apply that to this:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
This won't compile, but this is essentially what I want:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>(5)>(4);
My mediocre solution
To give the matrix some dimensions before I attempted to copy the list over, I just iterated for the number of rows I wanted and added a list of size of the number of columns I wanted to each row.
I used a regular array and converted it to an ArrayList just so that the elements would have a default value of null, and so would contribute to the size.
for (int r = 0; r < 4; r++) {
// list.add( new ArrayList<String>(5) ); // doesn't work
list.add( new ArrayList<String>( Arrays.asList(new String[5]) ) );
}
So that works for setting the size, because enough elements will be added to the matrix, but it's not the preferred solution.
The question
Is there any way to set the initial dimensions of an ArrayList of ArrayLists during the initialization? Or just something different that iterating and adding null values?
This works for me:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(4);
for (int r = 0; r < 4; r++) {
ArrayList<String> ls = new ArrayList<String>(5);
ls.add("" + (r + 1));
list.add(ls);
}
for (ArrayList<String> ls : list) {
System.out.println(ls);
}
Note: do not confuse ArrayList#size(), current number of elements in the collection, with ArrayList#capacity, current maximum size of the collection (which cannot be accessed).
For more info, refer to: ArrayList(int):
Constructs an empty list with the specified initial capacity.
Note that using List<List<Whatever>> you're not creating a 2D dynamic array, you're creating a dynamic list which will contains dynamic lists, thus you must initialize every list by separate and add lists (from any size) into another list, and every list would have a dynamic size (despite the values they have). There's no 2d dynamic array nor dynamic array of arrays in plain Java, unless you create such class or import it from a third party library.
Looks like this structure would suit better for your case:
String[][] stringArrayOfArray = new String[4][5];
Another very odd way (not recommended) to accomplish what you want/need would be:
List<String>[] arrayOfList = new List[4];
for (int i = 0; i < arrayOfList.length; i++) {
arrayOfList[i] = new ArrayList<String>();
}

int [] [] convert --to--> Vector<Vector<Double>>

I would like to convert an integer [] [] to a Vector<Vector<Double>>. After much reading, it seems no one has left a searchable post on the web for something of this nature. plenty of int vector to double vector, arraylist to vector, etc. Sadly I haven't found what i am looking for. So..Do any of you folks know an appropriate method for this? I was thinking of converting my int[][] to strings then convert that to vector<vector<Double>>. Opinions? Would something like this be useful, ie. converting my array to object array
Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), };
// Arrays.asList(Object[]) --> List
List l = Arrays.asList(a1d);
// Vector contstructor takes Collection
// List is a subclass of Collection
Vector v;
v = new Vector(l);
// Or, more simply:
v = new Vector(Arrays.asList(a1d));
Otherwise could you give me a better example that may have less steps? Thanks a Bunch again.
First of all: avoid Vector, it is obsolete; use ArrayList instead (or something simmilar).
Read more here
Secondly, if I had to convert a 2d array to a list of lists, I'd keep it very simple:
List<List<Double>> list = new ArrayList<ArrayList<Double>>();
for(int i=0; i<100; i++) //100 or whatever the size is..
{
List<Double> tmp = new ArrayList<Double>();
tmp = Arrays.asList( ... );
list.add( tmp );
}
I hope I understood your problem right.
Vector is an old class that is not deprecated but shouldn't be used anymore. Use ArrayList instead.
You should use the LIst interface rather than using the concrete Vector class. Program on interfaces, not on implementations.
Moreover, having repeating conversions like this shows a lack of design. Encapsulate your data into usable objects that don't need conversion each time you need a new functionality.
If you really need to do this: use loops:
int[][] array = ...;
List<List<Double>> outer = new Vector<List<Double>>();
for (int[] row : array) {
List<Double> inner = new Vector<Double>();
for (int i : row) {
inner.add(Double.valueOf(i));
}
outer.add(inner);
}
Transforming from int to STring and then from String to Double is wasteful.
A Vector is one dimensional.
You could have a Vector of Vectors to simulate a 2D array:
Vector v = new Vector();
for (int i = 0; i < 100; i++) {
v.add(new Vector());
}
//add something to a Vector
((Vector) v.get(50)).add("Hello, world!");
//get it again
String str = (String) ((Vector) v.get(50)).get(0);
Note: Vector is an old collection that is not recommended to be used

How to create an array of vector in Java?

So, I want an array of Vector of Integer in Java.
If I put
Vector<Integer>[] matrix;
matrix = new Vector<Integer>[100];
I get cannot the compilation error
cannot create a generic array of Vector
Should I use
matrix = new Vector[100];
instead? (which gives a warning)
Or should I simply not use an array of vectors and use vector of vector instead?
Note: I don't want a Vector< Integer >, I want a Vector< Integer >[] to create a matrix of Integers without using Integer[][].
Java simply doesn't have any means to create arrays of a parameterized type without getting or suppressing a warning. So the best you can get is this:
#SuppressWarnings("unchecked")
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector<Integer>[100];
You can get around this problem if you avoid arrays entirely. I.e.:
Vector<Vector<Integer>> list = new Vector<Vector<Integer>>(100);
Or with the collection types:
List<List<Integer>> list = new ArrayList<List<Integer>>(100);
Vector<Integer> vector = new Vector<Integer>();
If you try to do something like this:
Vector<Integer> vector = new Vector<Integer>();
Vector<Integer>[] vectors = {vector};
You will get a compile error:
Cannot create a generic array of
Vector
However if you don't specify the generic type java will allow it but with a warning:
Vector<Integer> vector = new Vector<Integer>();
Vector[] vectors = {vector};
Vectors are backed by arrays, and will grow or shrink to a size sufficent to hold the element you insert into it. As such, you can pre-allocate a Vector, but you do not have to actually specify the size at create time.
// preallocated vector, which can hold 100 elements
Vector<Integer> integers = new Vector(100);
.
// default vector, which will probably grow a couple of times when adding 100 element
Vector<Integer> integers = new Vector();
A true Java array cannot grow or shrink, and it doesn't support removal of an element from a mid-point. To allocate an Array, you use
// allocate an array
Integer[] integers = new Integer[100];
Now if you want to have an "array of vectors" then you would
// array of vectors
Vector[] vectors = new Vector[100];
To create an array of generic you have to create the non-generic and cast it. You also have to initialise all the elements in the array, otherwise they will be null. :(
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new Vector<Integer>();
However, since Vector is a legacy class which was replaced by ArrayList in Java 1.2 (1998) I would use List for the interface and ArrayList for the implementation.
List<Integer>[] anArray = (List<Integer>[]) new List[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new ArrayList<Integer>();
Another option would be to use a collection which held primitive int instead of Integer Objects. This can enhance performance if you need it.
TIntArrayList[] anArray = new TIntArrayList[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new TIntArrayList();
To avoid type casting, consider this implementation:
Vector<Integer>[] intVectorArray;
Vector[] temp = new Vector[desiredSize];
intVectorArray = temp;
for(int i = 0;i<intVectorArray.length;i++){
hashArray[i] = new Vector<Integer>();
}
The newly created intVectorArray will inherit the generic Vector-Array type of temp to give you your desired dimensions, and the for loop will instantiate your desired datatype.
When you're ready to call Integer functions on elements of intVectorArray, you will be all set!

Categories