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

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

Related

Java 2D arraylists

I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.

why assign ArrayList to new ArrayList temp

I am looking at the code for Permutations problem on leetcode. For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
And I found there is one sentence
ArrayList<Integer> temp = new ArrayList<Integer>(l);
I have no idea why here needs to assign the "l" to "temp". And I tried current.add(l) direclty but gave me the wrong answer. Can you help me with this?
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
//System.out.println(temp);
// - remove num[i] add
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
}
I have no idea why here needs to assign the "l" to "temp"
He's not - that would just be:
ArrayList<Integer> temp = l;
Instead, the code creates a copy of the content of the list l refers to, in a new ArrayList. That means that future changes to the list that l refers to (such as the call to l.remove(j) immediately afterwards) don't affect the new list.
As a simple stand-alone example of that, consider:
List<String> original = new ArrayList<>();
original.add("foo");
List<String> copy = new ArrayList<>(original);
System.out.println(copy.size()); // 1
original.add("bar");
System.out.println(copy.size()); // Still 1
Admittedly the code is written in a very odd manner - until the final statement, result only ever has a single element, so iterating over it is pretty pointless - but I believe that explains the single statement you were asking about.
If you did
current.add(l);
you would be adding the same reference to the ArrayList l to current. So, if you made some changes in one of those lists, both would be modified. In order to avoid that issue, in the line
ArrayList<Integer> temp = new ArrayList<Integer>(l);
you are creating a different ArrayList but with the same content. So, they will be different objects (different references).

Java / Printing a LinkedList node containing an array

public static void main(String[] args) {
LinkedList test = new LinkedList();
int[] numberPair;
numberPair = new int[2];
numberPair[0] = 1; numberPair[1] = 2;
test.add(numberPair);
}
How would I go about accessing the array in the first node of this list and printing it? I've tried all kinds of casting with test.getFirst(), but either it prints out the memory address or I get a long list of casting errors for objects.
Try using Arrays.toString().
See the javadoc for details.
Edit:
As other answers have pointed out, you should also use generics with your List. You should declare it as a LinkedList<int[]>. And then as you iterate over the elements, use Arrays.toString to convert each element into a string and print the result.
If using java 1.5+ use java generics like so:
LinkedList<int[]> test = new LinkedList<int[]>();
int[] top = test.getFirst();
for (int i: top){
System.out.print(i+" ");
}
System.out.println();
You should use a generic type instead of a raw type.
LinkedList<int[]> test = new LinkedList<int[]>();
When do test.getFirst(), you are getting an int array back, so just iterate through it.
int[] bla = test.getFirst();
for ( int i : bla )
System.out.println(i);
Or use
Arrays.toString(test.getFirst());

How can I create an Array of ArrayLists?

I am wanting to create an array of arraylist like below:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
But it's not compiling. How can I do this?
As per Oracle Documentation:
"You cannot create arrays of parameterized types"
Instead, you could do:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
As suggested by Tom Hawting - tackline, it is even better to do:
List<List<Individual>> group = new ArrayList<List<Individual>>(4);
As the others have mentioned it's probably better to use another List to store the ArrayList in but if you have to use an array:
ArrayList<Individual>[] group = (ArrayList<Individual>[]) new ArrayList[4];
You will need to suppress the warning but it's safe in this case.
This works:
ArrayList<String>[] group = new ArrayList[4];
Though it will produce a warning that you may want to suppress.
You can create a class extending ArrayList
class IndividualList extends ArrayList<Individual> {
}
and then create the array
IndividualList[] group = new IndividualList[10];
You can create Array of ArrayList
List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
outer[i] = new ArrayList<>();
}
This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.
In Java 8 and above you can do it in a much better way.
List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());
This works, array of ArrayList. Give it a try to understand how it works.
import java.util.*;
public class ArrayOfArrayList {
public static void main(String[] args) {
// Put the length of the array you need
ArrayList<String>[] group = new ArrayList[15];
for (int x = 0; x < group.length; x++) {
group[x] = new ArrayList<>();
}
//Add some thing to first array
group[0].add("Some");
group[0].add("Code");
//Add some thing to Secondarray
group[1].add("In here");
//Try to output 'em
System.out.println(group[0]);
System.out.println(group[1]);
}
}
Credits to Kelvincer for some of codes.
The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant
You can't create array of generic type. Create List of ArrayLists :
List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();
or if you REALLY need array (WARNING: bad design!):
ArrayList[] group = new ArrayList[4];
Creation and initialization
Object[] yourArray = new Object[ARRAY_LENGTH];
Write access
yourArray[i]= someArrayList;
to access elements of internal ArrayList:
((ArrayList<YourType>) yourArray[i]).add(elementOfYourType); //or other method
Read access
to read array element i as an ArrayList use type casting:
someElement= (ArrayList<YourType>) yourArray[i];
for array element i: to read ArrayList element at index j
arrayListElement= ((ArrayList<YourType>) yourArray[i]).get(j);
List[] listArr = new ArrayList[4];
Above line gives warning , but it works (i.e it creates Array of ArrayList)
To declare an array of ArrayLists statically for, say, sprite positions as Points:
ArrayList<Point>[] positionList = new ArrayList[2];
public Main(---) {
positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
positionList[1] = new ArrayList<Point>();
}
dynamically:
ArrayList<Point>[] positionList;
int numberOfLists;
public Main(---) {
numberOfLists = 2;
positionList = new ArrayList[numberOfLists];
for(int i = 0; i < numberOfLists; i++) {
positionList[i] = new ArrayList<Point>();
}
}
Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
You can create like this
ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];
You have to create array of non generic type and then cast it into generic one.
ArrayList<Integer>[] graph = new ArrayList[numCourses]
It works.
I think I'm quite late but I ran into the same problem and had to create an array of arraylists as requested by my project in order to store objects of different subclasses in the same place and here is what I ended up doing:
ArrayList<?>[] items = new ArrayList[4];
ArrayList<Chocolate> choc = new ArrayList<>();
ArrayList<Chips> chips = new ArrayList<>();
ArrayList<Water> water = new ArrayList<>();
ArrayList<SoftDrink> sd = new ArrayList<>();
since each arraylist in the array would contain different objects (Chocolate , Chips , Water and SoftDrink )
--it is a project to simulate a vending machine--.
I then assigned each of the Arraylists to an index of the array:
items[0]=choc;
items[1]=chips;
items[2]=water;
items[3]=sd;
Hope that helps if anyone runs into a similar issue.
I find this easier to use...
static ArrayList<Individual> group[];
......
void initializeGroup(int size)
{
group=new ArrayList[size];
for(int i=0;i<size;i++)
{
group[i]=new ArrayList<Individual>();
}
You can do thi. Create an Array of type ArrayList
ArrayList<Integer>[] a = new ArrayList[n];
For each element in array make an ArrayList
for(int i = 0; i < n; i++){
a[i] = new ArrayList<Integer>();
}
If you want to avoid Java warnings, and still have an array of ArrayList, you can abstract the ArrayList into a class, like this:
public class Individuals {
private ArrayList<Individual> individuals;
public Individuals() {
this.individuals = new ArrayList<>();
}
public ArrayList<Individual> getIndividuals() {
return individuals;
}
}
Then you can safely have:
Individuals[] group = new Individuals[4];
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
al[i] = new ArrayList<String>();
}
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.

Paramertized Types

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.

Categories

Resources