Paramertized Types - java

I am from a .Net background and do not understand the following snip. Can someone explain the <> and the following code to me as I just dont seem to get it. Sorry for dumb questions but this one I have been trying to understand all evening.
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < 3; i++) {
x.add(new double[] { 1, 2, 3, 4, 5, 6 });
}

They're the equivalent of C# generics. It's creating a list of double arrays, then adding [1,2,3,4,5,6] to it three times.

If you create a List<T> you can add instance of T to the list. In this case, T is double[].

In the Java programming language arrays are objects and may be assigned to variables of type java.lang.Object. Your code can also be written this way
Object numbers =new double[] { 1, 2,
3, 4, 5, 6 };
Your code
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < 3; i++) {
x.add(numbers);
}
Another variation: Here I created "x" as a List that can contain Object types. Since, arrays are subclasses of Object in Java, I can store the arrays in this list "x"
List<Object> x=new ArrayList<Object>();
for (int i = 0; i < 3; i++) {
x.add(numbers);
}

For a list, the type parameter in the <>'s indicates what type of objects should be stored in that list. List<double []> creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
Would add two double arrays to myList. So: myList.get(0) would return: {1,2,3}
and myList.get(1) would return: {4,5,6}.
If you are trying to just create a list of doubles, and not a list of double arrays, you would do:
List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);
Now myList.get(0) will return 1 and myList.get(1) will return 2. Notice that to create a list of a primitive type, you need to specify the object version of that primitive type in the type parameter. I.e., you can't do: List<double>
This is because all type parameters just get converted to Object by the compiler.

Related

what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array

I have an String Array and Integer Array,
String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?
In Java, String and Integer both are inherited from Object. So you can use Object type to define a general array.
String[] strArray = { "a", "b", "c" };
Integer[] intArray = { 1, 2, 3 };
Object[] arr = new Object[strArray.length + intArray.length];
int j = 0;
for (int i = 0; i < strArray.length; i++) {
arr[j++] = strArray[i];
}
for (int i = 0; i < intArray.length; i++) {
arr[j++] = intArray[i];
}
The first instinct would be to me:
In Java you just can have one Type for container, if you want to mix two types, you have to create some abstraction, like an Interface, or create another way to relate your String with your Integer.
But
consider the #kimdung answer if you just want to mix the two arrays and just this, and if you don't care anything else.
You need to use object type array, as in your case you are using integer wrapper object and string, which can be merge as object in java
Make a Sting array and merge both into that array, you will have to convert Integer to String while merging and the converse when you are retrieving for any purpose
for(int i=0; i<intArray.length; i++) {
mergerArray[i] = String.value(intArray[i]);
}
It is not possible to join two arrays of difference types. But I want to recommend you to use instances java.util.ArrayList instead of array. For example you can join these two different arrays.
ArrayList<Character> strArr= new ArrayList<Character>();
strArr.add(new Character('a'));
strArr.add(new Character('b'));
strArr.add(new Character('c'));
ArrayList<Character> intArr= new ArrayList<Character>();
intArr.add(new Character('1'));
intArr.add(new Character('2'));
intArr.add(new Character('3'));
//merge two arrays
strArr.addAll(intArr);
You can use System.arraycopy();
String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
Object[] objArray = new Object[strArray.length + intArray.length];
System.arraycopy( strArray, 0, objArray, 0, strArray.length );
System.arraycopy( intArray, 0, objArray, strArray.length, intArray.length );
Rather than type Object, you can change to desired type like String.

Defining an array of List of integers in Java

I have an array. For each element of the array, I want to store multiple integers. I know that in C I can make an array of integer pointers, and use that pointer to make a list.
In Java, I can make an array of object 'A', where A has a list of integers. But why can't I do something like this
List<Integer>[] arr = new ArrayList<Integer>[]();
I get:
Type mismatch: cannot convert from ArrayList to List[]
You typically want to avoid mixing collections and arrays together for this very reason; an array is covariant (that is, Integer[] is-an Object[]), but collections (and generics in general) are invariant (that is, a List<Integer> is not a List<Object>).
You can definitely create a list of lists instead, which will ensure type safety and get you around the issue of creating a generic array:
List<List<Integer>> intNestedList = new ArrayList<>();
As stated in Java's own documentation, you cannot create an array of generics.
If you want to create an array which can hold up to ten List<Integer> you must declare the array that way.
List<Integer>[] arr = new ArrayList[10];
following assignment is valid
List<Integer> intList = new ArrayList<>();
arr[0] = intList;
whereas following will fail with an compilation error
List<String> stringList = new ArrayList<>();
arr[0] = stringList;
the compilation fails with
incompatible types: java.util.List<java.lang.String>
cannot be converted to java.util.List<java.lang.Integer>
An ArrayList is a List, but an ArrayList is not a List[]
If you want an Array of Lists that hold integers, I would suggest:
List<Integer>[] xyz; // still writing code will update in a sec
It turns out you can't create arrays of parameterized types, according to the oracle docs.
Unless you know for sure you want a finite array, I suggest you do something like List<List<Integer>> arr = new ArrayList<List<Integer>>();
If you really want an array of Lists then you'll want to see this Java question about ArrayList<Integer>[] x
Creating an array of List is no different than creating an array of any other object. You can do any of the following:
List[] listsArray = new List[3];
listsArray[0] = new ArrayList();
listsArray[1] = new LinkedList();
listsArray[2] = new ArrayList();
Or:
List[] listsArray = new List[]{new ArrayList(), new LinkedList(), new ArrayList()};
Note that you are limited in what you can do with generics on arrays.
Not a very nice solution but you might try it with a cast. Something like this:
List<Integer>[] arr = (List<Integer>[]) new List[SIZE_OF_YOUR_ARRAY];
You will probably get a warning but it should still work.
As i found, you need an array of arrays.
you can do this, to make your inner arrays:
Integer[] array1 = new Integer[];
Integer[] array2 = new Integer[];
and then put them in another array like this:
Integer[][] arrays = new Integer[][] { array1, array2 };
or
Integer[][] arrays = { array1, array2 };
maybe it's better to do it like this:
List<List<Integer>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("123","456","789"));
after all I recommend you to read this:
How to make an array of arrays in Java
Graph Implementation using Adjacency List depicts the usage of an Array of List.
public class Graph {
int vertex;
LinkedList<Integer> list[];
public Graph(int vertex) {
this.vertex = vertex;
list = new LinkedList[vertex];
for (int i = 0; i <vertex ; i++) {
list[i] = new LinkedList<>();
}
}
}
As you can observe that the constructor of class Graph, is used to define the Array of List.
in the same constructor, Array Of List is initialized too.
Hope It would be Helpful to resolve your problem and requirement !.

[D cannot be cast to java.lang.Double

I wrote below code. It get this message:
Exception in thread "main" java.lang.ClassCastException: [D cannot be cast to java.lang.Double
double[] xyz = {1, 11, 111, 2, 22, 222};
ArrayList array = new ArrayList();
array.add(xyz);
double[] vals = new double[array.size()];
vals[0] = (double) array.get(0);
vals[1] = (double) array.get(1);
vals[2] = (double) array.get(2);
I have also search and see some post on Stack Overflow, but they do not make much me sense. What should I do?
If you want to add an array of double values to an ArrayList, do this:
Double[] xyz = {...};
ArrayList<Double> array = new ArrayList<>(); // note, use a generic list
array.addAll(Arrays.asList(xyz));
A List cannot store primitives, so you must store Double values not double. If you have an existing double[] variable, you can use ArrayUtils.toObject() to convert it.
Actually your problem is that you are trying to cast the type of 'xyz', which does not seems to be a double or the Wrapper associed (Double), into a double.
Since java can't transform the type of 'xyz' into a double a ClassCastException is throw. You should try to add n double to your array like that (or even in a loop) :
ArrayList<Double> myListOfDouble = new ArrayList();
myListOfDouble.add(1.0);
And then using a for loop to populate your double[] vals like this :
for(int i = 0; i < myListOfDouble.size(); i++)
vals[i] = myListOfDouble.get(i);

[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;

In my java code, I try to build a list of arraylist, my code is as follows,
private ArrayList<Integer>[] listoflist;
listoflist = (ArrayList<Integer>[]) new Object[875715];
However, when I compile the code, the compiler keeps saying that
[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;
Can I ask why I can not cast Object[] to ArrayList[]?
You said that you're trying to build a list of ArrayLists. But... you're trying to use an array to do that... Why not just use another ArrayList? It's actually pretty easy:
private List<List<Integer>> listoflist = new ArrayList<ArrayList<Integer>>();
Here's an example of using it:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(Integer.valueOf(3));
list1.add(Integer.valueOf(4));
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(Integer.valueOf(6));
list2.add(Integer.valueOf(7));
listoflist.add(list1);
listoflist.add(list2);
Saying ArrayList<ArrayList<Integer>> so many times is kinda weird, so in Java 7 the construction can just be new ArrayList<>(); (it infers the type from the variable you're assigning it to).
Java is a strong typed language - hence you cannot simply cast one type to the other.
However you can convert them.
In case of Object[] to List simply use
Object[] arr = new Object[]{...};
List<Object> list = Arrays.asList(arr);
and if you want to use it as an ArrayList, e.g. if you want to add some other elements, simply wrap it again
ArrayList<Object> arrList = new ArrayList<Object>(Arrays.asList(arr));
You can make an n-dimensional ArrayList, just like an n-dimensionaly Array, by putting ArrayLists into ArrayLists.
Here an example with 3 dimensions to show the concept.
public static void main(String args[]){
ArrayList<ArrayList<ArrayList<Integer>>> listOfListOfList = new ArrayList<ArrayList<ArrayList<Integer>>>();
int firstDimensionSize = 3;
int secondDimensionSize = 4;
int thirdDimensionSize = 5;
for (int i = 0; i < firstDimensionSize; i++) {
listOfListOfList.add(new ArrayList<ArrayList<Integer>>(vertices));
for (int j = 0; j < secondDimensionSize; j++) {
listOfListOfList.get(i).add(new ArrayList<Integer>());
for(int k = 0; k < thirdDimensionSize; k++) {
listOfListOfList.get(i).get(j).add(k);
}
}
}
}
Note that you can leave the <> empty after the new ArrayList<>. Java will infer the type (no matter how nested), since java 7 I believe. I just wrote them down in the example to show what type you are handling at every level, to make the example more clear. You can still write them down to make your code more readable.
define it in single line like following, compiler doesn't complain
private ArrayList[] listoflist = (ArrayList<Integer>[]) new Object[10];

Can we have an Array of a collection?

I was trying create an array of a collection as follows.
ArrayList<Integer> ar[]=new ArrayList<Integer>[50];
but it gives me an error -> generic array creation
can anybody explain me why is it?
You can't create arrays of generic types. Use collection of collections instead:
ArrayList<ArrayList<Integer>> = new ArrayList<ArrayList<Integer>>();
Why can't we create an array of generic type? Array stores they exact type internally, but due to the type erasure at runtime there will be no generic type. So, to prevent you from been fooled by this (see example below) you can't create an array of generic type:
//THIS CODE WILL NOT COMPILE
ArrayList<Integer>[] arr = new ArrayList<Integer>[5];
Object[] obj = arr;
obj[0] = new ArrayList<Long>(); //no one is safe
ArrayList is internally a 1D array itself. what you need 2D array so you can create
ArrayList<Integer[]> ar=new ArrayList<Integer[]>();
or
ArrayList<ArrayList<Integer>> = new ArrayList<ArrayList<Integer>>();
The answer to you question can be found in the Java Language Specification. You are trying to create an array using Array Creation Expression. It says the following: "It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type". Because arrays in Java are created at runtime, their type information should be completely available at runtime. In other words array element type should be a reifiable type. Generics in Java are implemented using type erasure (i.e. only subset of generics compile-time type information is available at runtime) hence they are not reifiable by definition and therefore you cannot create arrays of generic types.
Actually you can have an Array of Collection, it just is not allowed that the Collection has a specific type.
You can do something like
ArrayList<?>[] ar = new ArrayList<?>[50];
// or ArrayList[] ar = new ArrayList[50];
ar[0] = new ArrayList<Integer>();
but you will not have the benefits of Generics - there is no type information for the content of the Collection, you will need to cast when reading from it
Integer i = (Integer) ar[0].get(0);
You could do something like this
ArrayList<Integer> ar[]= new ArrayList[50];
ArrayList<Integer> intArr = new ArrayList<Integer>();
ArrayList<Long> longArr = new ArrayList<Long>();
ar[0]=intArr;
ar[1]= longArr; // compile error Type mismatch: cannot convert from ArrayList<Long> to ArrayList<Integer>
You can have an array "technically" of type ArrayList but its a bit nit picky. Create it as an ArrayList<ArrayList<Integer>> list = ArrayList<ArrayList<Integer>(); and convert it using toArray(ArrayList<Integer>[list.size()]);.
Example:
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
int count = 1;
for(ArrayList<Integer> AList: list) {
for(int i = 0; i < 4; i++)
AList.add(count++);
}
ArrayList<Integer>[] check = list.toArray(new ArrayList[list.size()]);
for(ArrayList<Integer> AL : check) {
for(Integer i:AL) {
System.out.print(i + " ");
}
System.out.println();
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Works and is an ArrayList array

Categories

Resources