Processing language: Get inner array values from ArrayList() - java

I'm trying to use the ArrayList() method in Processing.
I have this:
ArrayList trackPoints = new ArrayList();
//inside a loop
int[] singlePoint = new int[3];
singlePoint[0] = 5239;
singlePoint[1] = 42314;
singlePoint[2] = 1343;
//inside a loop
trackPoints.add(singlePoint);
So basically I want to add an array "singlePoint" with three values to my ArrayList.
This seems to work fine, because now I can use println(trackPoints.get(5)); and I get this:
[0] = 5239;
[1] = 42314;
[2] = 1343;
However how can I get a single value of this array?
println(trackPoints.get(5)[0]); doesn't work.
I get the following error:
"The type of the expression must be an array type but it resolved to Object"
Any idea what I'm doing wrong? How can I get single values from this arrayList with multiple arrays in it?
Thank you for your help!

Your ArrayList should by typed :
List<int[]> list = new ArrayList<int[]>();
If it's not, then you're using a raw List, which can contain anything. Its get method thus returns Object (which is the root class of all the Java objects), and you must use a cast:
int[] point = (int[]) trackPoints.get(5);
println(point[0]);
You should read about generics, and read the api doc of ArrayList.

The get() method on ArrayList class returns an Object, unless you use it with generics. So basically when you say trackPoints.get(5), what it returns is an Object.
It's same as,
Object obj = list.get(5);
So you can't call obj[0].
To do that, you need to type case it first, like this:
( (int[]) trackPoints.get(5) )[0]

Related

misunderstanding the generic in java

I am trying to understand generics in Java.
private List<Own> l = new ArrayList<Own>();
I have the following error :
no instance of Typed array variable T exist so that List<Own> conform to T[]
when I pass it in a method (readTypedArray) that expects T[].
private List<Own> list = new ArrayList<Own>();
private OwnParceable(Parcel in) {
in.readTypedArray(list, CategoriesParceable.CREATOR);
}
The method in.readTypedArray() expects an array T[], but you passed a List<Own which is not an array.
List is not an array you can't use it where an array is expected, List is an interface which extends Collection while array is a data structure in Java, check Difference between List and Array for further details.
You can either declare an Own[]instead of List<Own> or convert this list into an array before passing it to the method, check Convert list to array in Java:
in.readTypedArray(list.toArray(new Own[list.size()]), CategoriesParceable.CREATOR);
This has nothing to do with generics - Lists and arrays are just two different things. If your method expects an array, you need to pass it an array, not a List:
Own[] arr = new Own[10]; // Or some size that makes sense...
in.readTypedArray(arr, CategoriesParceable.CREATOR);
There is a possibility to create an array filled with content of specified List. To achieve that you can call method toArray() of your list reference, for example:
Integer[] array = list.toArray(new Integer[list.size()]);

How to create an array of objects of a specific class type

I have a function that returns an Object. The Object can contain an array of primatives or an array of objects. In C# I can create an empty array of objects or primatives using code like:
Array values = Array.CreateInstance(/*Type*/type, /*int*/length);
Is there an equivalent in Java?
How to create an array of objects of a specific class type
Test[] tests = new Test[length] ;
And if you want to have a mix up of Primitives and Objects, though it is not suggestable, If you want to mix primitives with Objects
Object[] objs = new Object[length];
That allows you to both primitives(in form of wrappers) and normal Objects together.
If you have a class called Test of your own, you can create an array of Test's like
Note that until you initialise the elements in that array, they have null as their value.
Assuming you only know the element type at execution time, I think you're looking for Array.newInstance.
Object intArray = Array.newInstance(int.class, 10);
Object stringArray = Array.newInstance(String.class, 10);
(That will create an int[] and a String[] respectively.)
Object[] array = new Object[length];
Or with your own type:
MyType[] array = new MyType[length];

Can someone break down this line so I can understand it?

I'm having trouble understanding how an array of ArrayLists is initialized in Java, can someone explain what's going on in this line of code?
edges = (ArrayList<Integer>[]) new ArrayList[nodeCount + 1];
Let's break it space-by-space.
edges is a variable of type ArrayList<Integer>[]
= is the assign operator which assignes the right-hand to the left-hand
(ArrayList<Integer>[]) is a cast of a variable to the type.
new ArrayList[nodeCount + 1] means we allocate space for an array of ArrayList with nodeCount+1 unknown elements.
This is a very bad way of initializing an array. What it does is it creates an array and makes the elements into Integers.
An alternative:
edges = new ArrayList<Integer>(nodeCount+1);
Explanation: The ArrayList class has a constructor which can specify its length*, this is what I use here.
Note: According to #Rohit Jain, it doesn't specify the length, but the initial capacity.
You cannot create an array whose component type is parameterized type. It's not type safe. Although you can create an array whose component type is raw type, but that won't be type safe either. Consider the following example:
List<Integer>[] list = null; // Declaration is OK
list = new ArrayList<Integer>[5]; // Compiler error: Generic array creation
list = new ArrayList[5]; // Compiles fine. But not safe. Gives warning
Suppose you created an array of raw types. Let's see what can be the implication:
List<Integer>[] list = new ArrayList[10]; // Not type safe
Object[] objArr = list; // We can assign List<Integer>[] to Object[]
// We can add even ArrayList<String> in Object[]
// This will successfully compile, and run.
objArr[0] = new ArrayList<String>() {
{
add("rohit"); add("jain");
}
};
// Here's the problem. It will compile fine, but at runtime will throw
// ClassCastException
Integer val = list[0].get(0);
Alternative is create a List of List:
List<List<Integer>> edges = new ArrayList<List<Integer>>();
Suggested Read: -
Angelika Langer Generic FAQs:
Can I create an array whose component type is a concrete parameterized type?
Can I declare a reference variable of an array type whose component type is a concrete parameterized type?
In the above line you are creating an array of ArrayList, you could replace ArrayList by a more simple type to help you to understand, e.g. an array of String:
edges = (String[]) new String[nodeCount + 1];
nodeCount + 1 corresponds to size of the array. The array can't have more than this number of elements.
Note that using an array of a parametrized ArrayList is quite strange and prone to misunderstanding and errors. I would use a List<List<Integer>> here, e.g.:
edges = new ArrayList<List<Integer>>();
this line defines an array, like any other array out there: exampe new Object[0], new String[0], ...
and just like any other array, the values will be initiated with the null value. for primitive types is that '0', for objects/classes is that null.
so you should initiate the different arraylists before using it like:
edges = new ArrayList<Integer>[nodeCount + 1];
for(int i=0; i<edges.length; i++){
edges[i] = new ArrayList<Integer>();
}
This does not initialize an ArrayList -- it initializes an array of ArrayLists:
new ArrayList[nodeCount + 1] = create an array of ArrayList objects with nodeCount + 1 slots
(ArrayList<Integer>[]) = cast it to an "array of ArrayList objects which in turn may only contain Integer objects". This is needed because the array declaration syntax of java apparently can't handle generics (just tried it -- I never needed this before).
It could be a misunderstanding, and the writer actually wanted to initialize one ArrayList with a capacity of nodeCount+ 1. The correct code for that would be
edges = new ArrayList<Integer>(nodeCount + 1);
Actually the capacity parameter is just an optimization, since ArrayList objects grow automatically as needed. But if you already know how many entries you need, the List can be created with enough capacity from the start.
new ArrayList[nodeCount + 1]
create a new array of ArrayList, its length is nodeCount + 1;
then
(ArrayList<Integer>[])
is a cast operation, it casts the array you just created into an array of ArrayList<Integer>

How to initialize an array of lists with a specific type?

I have a method that needs to return List<'MyClass>[] and need to set up a local variable to do so, but am having trouble with initialization.
I tried:
List<MyClass>[] lists = new List<MyClass>[5];
Which gave me an error of "Cannot create a generic array of List"
I tried casting an array of Objects:
List<MyClass>[] lists = (List<MyClass>[]) new Object[5];
Which gave me a casting error in runtime.
I also tried:
List<MyClass>[] lists = (List<MyClass>[]) new List[5];
Which resulted in a null pointer exception.
Anyone know what needs to be done to get this to work?
Thanks.
You declare a list like so (for example ArrayList):
List<MyClass> list = new ArrayList<MyClass>();
To create an array of this list you do:
List<?>[] listArray = new List<?>[]{list};
This will put your list in an array. I'm assuming that's what you want and not simply items from the list.

This is a legal way to initialize an array. But how would I access its elements?

I am preparing for the entry-level Oracle certification - OCA - Java Programmer I, since they require people to take this one before taking the next one (used to be possible to just go for SCJP directly, which is equivalent of OCP - Java Programmer II)
I came across this question on array initialization, that got me a bit puzzled. Obviously, one can declare and initialize an array like this:
Object[] objects = { new Object[1], new Object[34] };
as the arrays are objects, you can stick object arrays into an object array. You can easily get at one or the other object array by doing objects[0] or objects[1] but where would you go from there? How would you access the, say, 16th Object from the object array stored under objects[1]?
Basically, my question can be simplified to this:
Object o = new Object[100];
The above compiles. However, how would one access individual objects in the Object array o?
An Object[] is also an Object, which is why your declaration
Object o = new Object[100];
works.* To access the elements, though, you need to cast it back to an Object[]. For example:
Object elt = ((Object[]) o)[3];
For your original declaration:
Object[] objects = { new Object[1], new Object[34] };
you will have to do a similar thing to access the 16th element of objects[1]:
Object elt = ((Object[]) (objects[1]))[15];
Of course, you can avoid all this casting by declaring:
Object[][] objects = { new Object[1], new Object[34] };
in the first place. Then you can just do objects[1][15].
* Note that this is true only of Object, which has special status as the root of the object hierarchy in Java. An Integer[] cannot be assigned to an Integer variable.
You'd have to cast it back to Object[]:
Object o = new Object[] {new String("abc"), null, new Integer(1)};
Object[] arr = (Object[]) o;
Object elem = arr[0];
System.out.println(elem);
This prints abc.
It works because System.out.println() is happy to take an Object. If it required a String, you'd need another downcast.

Categories