How to convert java ArrayList to an array? - java

I have an ArrayList created like this:
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList list1 = new ArrayList();
list1.add(0, 5);
list1.add(1, 3.5);
list1.add(2, 10);
}
}
I am trying to create an array from it, using the toArray method:
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList list1 = new ArrayList();
list1.add(0, 5);
list1.add(1, 3.5);
list1.add(2, 10);
Double[] list2 = list1.toArray(new Double[list1.size()]);
}
}
However, I am getting an error:
(Error:(16, 39) java: incompatible types: java.lang.Object[] ).
So I tried to cast the right side to double:
Double[] list2 = (Double[]) list1.toArray(new Double[list1.size()])
This time i am getting Exception in thread "main". I also tried to declare my ArrayList as double from beginning:
ArrayList<double> list1 = new ArrayList()<double>
With no success. How to do it properly? I know that my problem is probably something very basic.

The problem is that you are doing a number of things wrong:
ArrayList list1 = new ArrayList(); is incorrect because you are using a raw type. You should have gotten a compiler warning for that.
Given the previous list1.add(0, 5) is incorrect. The 5 will be boxed as an Integer because that compiler doesn't know that the list is only supposed to contain Double values.
You were getting this:
(Error:(16, 39) java: incompatible types: java.lang.Object[] ).
because you must have done something like this:
Double[] list2 = list1.toArray();
You appear to have corrected that in the code that you posted. But the no-args toArray method returns an Object[] containing the list content.
ArrayList<double> list1 = new ArrayList()<double> is incorrect because you cannot use a primitive type as a generic type parameter, and because the syntax on the RHS is wrong.
The correct version is ArrayList<Double> list1 = new ArrayList<>(); with an empty diamond.
Surprisingly, the best (most efficient) way to code the toArray is:
Double[] list2 = list1.toArray(new Double[0]);
Apparently, the implementation is able to initialize the array faster if it allocates it itself. (Or so I have heard ...)

Related

incompatible types: List<Integer> cannot be converted to ArrayList<Integer> for Java sublists

I have been having this issue which I am not able to resolve at the moment. It is a type mismatch between List and ArrayList. I am not too sure of what went wrong with my work. Any help will be appreciated.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
// Sum of array
static Integer sumArray(ArrayList<Integer> Array){
Integer sum=Integer.valueOf(0);
for(int i=0;i<Array.size();i++){
sum+=Array.get(i);
}
return sum;
}
public static void main(String[] args){
ArrayList<Integer> RideArr = new ArrayList<Integer>(); // Initializing array
// Print out the RideArr values in list format(~)
RideArr.add(1);
RideArr.add(2);
RideArr.add(3);
RideArr.add(4);
RideArr.add(5);
ArrayList<Integer> jack=RideArr.subList(0, 4);
System.out.println(sumArray(jack));
}
}
Error: incompatible types: List cannot be converted to
ArrayList
ArrayList jack=RideArr.subList(0, 4);
The type of a variable should pretty much never be ArrayList. ArrayList is one specific kind of list implementation. someList.subList(a, b) does not return an ArrayList. It returns a List just fine, it's just not exactly an arraylist. Even ArrayList's own subList does not, itself, return an ArrayList.
It shouldn't matter what the implementation is, hence, using ArrayList anywhere is wrong; except with new ArrayList, as you can't write new List - with new, that is the one time you need to tell java what kind of list implementation you want. Thus:
List<Integer> rideArr = new ArrayList<>();
List<Integer> jack = rideArr.subList(0, 4);
NB: We write TypesLikeThis and variablesLikeThis, so, rideArr, not RideArr.
Try this one:
ArrayList<Integer> jack = new ArrayList<>(RideArr.subList(0,4));
System.out.println(sumArray(jack));

Raw and Generic List

This is a code just to know what is wrong and what is right.
public class JavaApplication5 {
public static void main(String[] args) {
List l=new ArrayList<String>();//Line 1
List<Object> x=new ArrayList<String>();//Line 2
}
}
In the above line 1 is working fine but line 2 gives me compilation error. Can you tell me why?
Are not List and List<Object> equivalent? Either both should be wrong or both should be correct.
You have to set the same Type in the both place :
List<Object> x = new ArrayList<String>();
//----^-------------------------^--------
So you have to option to solve your problem :
One don't set any type in your ArrayList
List<Object> x = new ArrayList<>();
Or set the same type :
List<Object> x = new ArrayList<Object>();
//or
List<String> x = new ArrayList<String>();
Neither posted option. For a List of String(s), since Java 7, you can use the diamond operator - like,
List<String> x = new ArrayList<>();
However, the older
List<String> x = new ArrayList<String>();
is still legal.
Your first option is a raw type, and your second option (if it were legal) makes a List that can contain any type of Object (not just 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 !.

Need clarification on addAll methods behaviour

Hi i am using addAll method of Collection framework. Please find below my code. It is working fine for code 1. For code 2 it is giving me compilation error. I dont know why it didnt give me error for code 1. Kindly give the reason for this.
code 1
public static void main(String[] args) {
List<Integer> firstList=new ArrayList<Integer>();
List secondList=new ArrayList(); //without generic
secondList.add("string value");
firstList.addAll(secondList);
System.out.println(firstList);
}
Output:
[string value]
Code 2
public static void main(String[] args) {
List<Integer> firstList=new ArrayList<Integer>();
List<String> secondList=new ArrayList<String>(); //with generic
secondList.add("string value");
firstList.addAll(secondList);
System.out.println(firstList);
}
Output
compilation error
Java Generics are checked on compile time. means compiler can check the generic list and can show an error if String List is to Integer. While in the first case . it is a non-generic, which compiler cannot judge at compile time.
Also read about Type Erasure
firstList.addAll(secondList);
firstList is type of string
secondList is type of numbers
In the first example you are using raw type but in the second you are using generics(specified list is for strings)
SEE HERE
If you use generics checking donet at compile time .If you use raw list it will done at runtime
List secondList=new ArrayList(); //without generic
It means List<Object> secondList=new ArrayList<Object>(); so you can add any object to this.
But if you explicitly mention the type it is clear that you can't add string to integer list, in your second case
You are trying to add all values from String bucket to a bucket which is specially allocated for Integer.
You can do like this
ArrayList commonList =new ArrayList(); // for all objects
List<String> stringList =new ArrayList<String>();
List<Integer> integerList =new ArrayList<Integer>();
stringList.add("string value");
integerList.add(1);
commonList .addAll(stringList);
commonList .addAll(integerList);
System.out.println(commonList );

How to reclaim the generic type you declared an arraylist to be in Java?

I was just playing around and a thought came to my mind and I decided I want to try it:
Make an ArrayList that holds more ArrayLists.
For example, I created an ArrayList called intList that holds ints, then filled it with values. After that I did a stringList one and filled it too. Then I made an ArrayList that holds other ArrayLists called aList and added intList and stringList to it.
Now the problem I faced was if I was retrieving objects from aList, it would not recognize if the generic type was int or string.
Here is the code I tried:
import java.util.*;
public class Practice {
public static void main(String[] args) {
List<ArrayList> list = new ArrayList<ArrayList>();
ArrayList<int> intList = new ArrayList<int>();
intList.add(1);
intList.add(2);
intList.add(3);
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("One");
stringList.add("Two");
stringList.add("Three");
list.add(intList);
list.add(stringList);
for(ArrayList lst : list) {
for(ArrayList lt : lst) {
System.out.println(lt);
}
}
}
}
Java has "generic type erasure", meaning that the type parameters to generics are "erased". Once you create an ArrayList<T> there's no way to find out what T was.
Only class types can be used as generic type parameters, so you can't have an ArrayList<int>. Use an ArrayList<Integer> instead.
In addition, the types used in your loops are wrong. Since list is a list of lists of values, lst is a list of values, which means that your lt variable will be either an integer or a string, not another ArrayList.
The deeper problem here is that you're still using raw types, so the compiler can't find that error for you. You should declare list as something like List<List<? extends Object>>. That way you can add both an ArrayList<Integer> and an ArrayList<String> to it, and extract the values as type Object within your loop.
Since no type information is stored in generic type, you could get element from sub-list and check it's type:
for(ArrayList subList : list) {
if (subList.size() > 0) {
Class elementClass = subList.get(0).getClass();
// do something else with it
}
}
But:
It will not work, if subList is empty
Generally, the concept of storing several lists of different types in another list looks rather strange.
Type erasure means that at runtime, the type is erased. That's why you can cast from one generic to another:
import java.util.ArrayList;
public class Test {
public static void main(String [] args){
ArrayList<String> list = new ArrayList<String>();
ArrayList list2 = (ArrayList)list;
list2.add(new Integer(5));
System.out.println(list2.get(0).getClass());
}
}
Will output:
class java.lang.Integer
import java.util.*;
public class Practice {
public static void main(String[] args) {
List<ArrayList<?>> list = new ArrayList<ArrayList<?>>();
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("One");
stringList.add("Two");
stringList.add("Three");
list.add(intList);
list.add(stringList);
for(ArrayList<?> lst : list) {
for(Object lt : lst) {
System.out.println(lt);
}
}
}
}

Categories

Resources