How to create an array of vector in Java? - 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!

Related

how to add a matrix to an ArrayList in 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!

Storing an ArrayList in an 2d Array Java

How can I store an ArrayList in a two dimensional array?
I've tried it like this, but it won't work:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];
but it won't even let me declare the ArrayList-Array.
Is there a way to store a list in a 2d array?
Thanks in advance!
You can't create arrays of generic types in Java. But this compiles:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;
Why can't you create these arrays? According to the Generics FAQ, because of this problem:
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal
Object[] objArr = intPairArr;
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed
Assuming you want an ArrayList inside an ArrayList inside yet another ArrayList, you can simply specify that in your type declaration:
ArrayList<ArrayList<ArrayList<Integer>>> foo = new ArrayList<ArrayList<ArrayList<Integer>>>();
Entries can be accessed via:
Integer myInt = foo.get(1).get(2).get(3);
Just be wary of boundaries - if you try to access an out of bounds index you'll see Exceptions thrown.

Questions about ArrayList

I need to use an ArrayList, but I am not sure how to do some of these things that would be possible with a normal array.
1) This:
int[][] example1 = new int[10][20];
(An array with two arguments (10, 20)) is possible with normal arrays, but how to do it with an ArrayList.)
2) How to increase the value of an int on the list by 1, like this:
example2[3][4] ++;
ArrayList is dynamically growable list backed by array.
List<List<Integer>> list = new ArrayList<List<>>(10);
you can get an element of list by List#get.
List<Integer> innerList = list.get(3);
Integer integer = innerList.get(4);
Update value by List#set -
list.get(3).set(4,list.get(3).get(4)++);
NOTE : Integer class is immutable.
To mimic a multidimensional array using collections you would use:
List<List<Integer>> list = new ArrayList<>(); //Java 7
List<List<Integer>> list = new ArrayList<List<Integer>>(); //Pre Java 7
So lets say we create a List<List<Integer>> where the outer List contains 10 List<Integer> and the inner list contains 10 Integers. To set the fifth element on the fourth list:
public static void main(String[] args) {
List<List<Integer>> outer = new ArrayList<List<Integer>>();
for(int x = 0; x < 10; x++){
List<Integer> inner = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
outer.add(inner);
}
//Remember that Integer is immutable
outer.get(3).set(4, new Integer(outer.get(3).get(4)) + 1);
}
int[][] example1 = new int[10][20]; you can do it in arraylist by using this syntax :
ArrayList<ArrayList<Integer>> ex = new ArrayList<ArrayList<Integer>>();
example2[3][4] ++; This can be same in arraylist as by using this :
int val = (a.get(0).get(0)) + 1;
The equivalent of your declaration with an ArrayList is:
List<List<Integer>> example1 = new ArrayList<>();
You have to use Integer because Java Collections do not support primitive types. Check out this page of the Oracle docs for more information on Autoboxing and Unboxing.
Since an ArrayListcan grow dynamically, you don't need to give a size. If you want it to have an initial size, you can pass that as an argument to the constructor.
You can get elements from an ArrayList (or any Class implementing the List interface) by using the get() method with the index of the element as an argument.
Using example.get() on example1 will give you an object of the type List. You can then use get() again to get an Integer.

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 filter an array in Java?

How can I filter an array in Java?
I have an array of objects, for example cars:
Class:
public class Car{
public int doors;
public Car(int d){
this.doors = d;
}
}
Use:
Car [] cars = new Cars[4];
cars[0] = new Car(3);
cars[1] = new Car(2);
cars[2] = new Car(4);
cars[3] = new Car(6);
Now I want to filter the array of cars, keeping only 4 doors and more:
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
}
}
How should I do this?
Before I did it with a Vector:
Vector subset = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
subset.addElement(cars[i]);
}
}
And then I would make a new array with the size of the Vector. Then I would loop over the vector again and fill the new array. I know this is a very large procedure for something simple.
I'm using J2ME.
EDIT: saw that ArrayList is not in J2ME, but based on documentation, it does have a Vector. If that Vector class is different than J2SE Vector (as this documentation indicates), then perhaps the following code would work:
Vector carList = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
carList.addElement(cars[i]);
}
}
Car[] carArray = new Car[carList.size()];
carList.copyInto(carArray);
The most efficient way to do this--if the predicate you're filtering on is inexpensive and you're accessing it with a single thread--is usually to traverse the list twice:
public Car[] getFourDoors(Car[] all_cars) {
int n = 0;
for (Car c : all_cars) if (c.doorCount()==4) n++;
Car[] cars_4d = new Car[n];
n = 0;
for (Car c : all_cars) if (c.doorCount()==4) cars_4d[n++] = c;
return cars_4d;
}
This traverses the list twice and calls the test twice, but has no extra allocations or copying. The Vector-style methods traverse the list once, but allocates about twice the memory it needs (transiently) and copies every good element about twice. So if you are filtering a tiny fraction of the list (or performance isn't an issue, which very often it isn't), then the Vector method is good. Otherwise, the version above performs better.
If you really need a plain array as the result, I think your way is the way to go: you don't know the number of resulting elements before you filter, and you can't construct a new array without knowing the number of elements.
However, if you don't need thread-safety, consider using ArrayList instead of a Vector. It ought to be somewhat faster. Then use ArrayList's toArray method to get the array.
I can't see much wrong with your code. You could just stick with Vectors throughout though.
You could simplify the second part (where you copy the matching items into the new array) using Vector.copyInto(Object[]).
There's no direct way to remove elements from an array; its size is fixed. Whatever you do, you need to allocate a new array somehow.
If you want to avoid the minor memory overhead of allocating a Vector, another option would be to make two passes over your array. The first time, simply count the number of elements that you want to keep. Then allocate an array that size, and loop over your old array again, copying matching elements into the new array.
You can use System.arrayCopy():
Car[] cars = ...
int length = cars.length < 4 ? cars.length() : 4;
Car filter = new Car[4];
System.arrayCopy(cars, 0, filter, 0, length);
UPDATE: System.arrayCopy is available in Java ME API, unlike Vector.subList(). Thanks for the correction.
You will need to create a new array anyway.
Vector vector = new Vector(array.length);
for (int i = 0; i < array.length; i++) {
if (array[i].doors > 4) {
vector.add(array[i]);
}
}
Car[] result = new Car[vector.size()];
vector.copyInto(result);
This isn't quite efficient, though.

Categories