misunderstanding the generic in java - 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()]);

Related

Java Generics : Convert Object Array to Primitive Array based on type

I want to convert an Object array to primitive array based on type of elements present in array.
I want to implement a function which takes Object array and type(as String) as inputs and should return the actual array i.e
func(Object[] arr, String type) should be implemented so that when I call
func(Object[] arr, "int"), it should return int[]
func(Object[] arr, "double"), it should return double[] etc.
Is it possible to do this and if not what can be done to obtain primitive array from Object[] ?
Edit : The use case I have is I need to create 'n' objects of class A which has certain fields(lets say 2). I get fields as Object arrays of length n i.e
Object[] field1
Object[] field2
I also get type of field in String format("int" or "double" etc) which is primitive always. Now can we create objects of class A and if possible how?
Instead of pre-allocating an array, I would suggest using a collection like ArrayList and then generate the resultant array into it.
ArrayList field1Array = Arrays.stream(arr).map(Object::field1)
If there are more fields that need to be allocated, then...
ArrayList field1Array = new ArrayList();
ArrayList field2Array = new ArrayList();
Arrays.stream(arr).forEach(object -> {
field1Array.add(object.getField1());
field2Array.add(object.getField2());
})

how internally arraylist stored different data types using an array [duplicate]

This question already has answers here:
How does ArrayList work?
(11 answers)
Closed 3 years ago.
how internally arraylist stores different data types using array. Since array is the internal implementation of an array list and in an array we can store only similar data type like string/int etc.
want to understand internal implementation of arraylist for handling data of multiple data types.
My question is actually: in a list we can add Integer, String, Boolean, anything, but internally it is implemented by an array. So how an array handles different types of wrapper into same array object.
ArrayList is a generic type.
So it can't work with primitive type.
It work with object type and use array object for internal implementation.
Object elements[]= new Object[size];
For example custom list:
public class MyList{
private static final int DEFAULT_CAPACITY = 10;
private Object elements[];
public MyList() {
elements = new Object[DEFAULT_CAPACITY];
}
}
ArrayList always requires object to store it in the list, It uses generics to create a list for specific type. For Example:
ArrayList<Integer> intList = new ArrayList<>();
This creates a arraylist for Integer type, here Integer is a wrapper class for the primitive data type int, we can't create arraylist of primitive type, we need to use a wrapper class. If you don't use generics then:
ArrayList<> intList = new ArrayList<>();
by default, it's get created for the Object class, which is super class of all the classes including the wrapper one.
Now:
ArrayList a = new ArrayList<>();
a.add(1);
Here, we created a arraylist of object, but adding 1 primitive integer, it's still valid because it's get converted into the Integer wrapper and Object is the superclass of Integer wrapper class. So if you write :
Object ab = new Object();
ab=1;
it's valid. so when you add 1 into the arraylist, your primitive 1 get's converted into the Integer wrapper class refered by Object class.
I hope this simplifies you.
In Addition with your comment, In the ArrayList class source code, you can see the array which stores all the element is nothing but:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
It's a Object class's array. So it can store any object and since, the ArrayList class implement the generics, it's easy to convert this object to the specific type, if the ArrayList is created with specific one.

Collection.toArray() method, detail about it

Why would not it work?
List<String> lista = new ArrayList<>();
lista.add("Lol");
lista.add("ball");
String [] array = (String[])lista.toArray();
It throws a RunTimeException (ClassCastException), I am aware that there is another method for the purpose of returning the object contained in the List, however what is happening behind the scenes? I mean I am casting an array of Objects which actually is an array of Strings to an Array of Strings. So it should compile, but it does not.
Thanks in advance.
That version of toArray() returns Object[]. You can't cast an Object array into a String array even if all the objects in it are Strings.
You can use the lista.toArray(new String[lista.size()]); version to get the actual type correctly.
List.toArray()
returns an Object[], because of type erasure. At runtime your list does not know if it has String objects. From there you can see where that error is coming from.
You cannot type cast an Object[] into a String[]
Array of objects is not array of Strings and can't be cast to one.
Check this.
use toArray(T[] a) instead.
Ie.
List<String> lista = new ArrayList<String>();
lista.add("Lol");
lista.add("ball");
String [] array = lista.toArray(new string[1]);
This insures that toArray returns an array of type String[]
As others have noted, toArray() returns an array of type Object[], and the cast from Object[] to String[] is illegal.
List lista = new ArrayList<>(); ---> List lista = new ArrayList();
There are two toArray() versions.You can use another one!

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

What is the difference between
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); // Copy
List<Integer> list2 = Arrays.asList(ia);
, where ia is an array of integers?
I came to know that some operations are not allowed in list2. Why is it so?
How is it stored in memory (references / copy)?
When I shuffle the lists, list1 doesn't affect the original array, but list2 does. But still list2 is somewhat confusing.
How does ArrayList being upcasted to list differ from creating a new ArrayList?
list1 differs from (1)
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
First, let's see what this does:
Arrays.asList(ia)
It takes an array ia and creates a wrapper that implements List<Integer>, which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, some List operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.
Note that the list wrapper doesn't extend ArrayList - it's a different kind of object. ArrayLists have their own, internal array, in which they store their elements, and are able to resize the internal arrays etc. The wrapper doesn't have its own internal array, it only propagates operations to the array given to it.
On the other hand, if you subsequently create a new array as
new ArrayList<Integer>(Arrays.asList(ia))
then you create new ArrayList, which is a full, independent copy of the original one. Although here you create the wrapper using Arrays.asList as well, it is used only during the construction of the new ArrayList and is garbage-collected afterwards. The structure of this new ArrayList is completely independent of the original array. It contains the same elements (both the original array and this new ArrayList reference the same integers in memory), but it creates a new, internal array, that holds the references. So when you shuffle it, add, remove elements etc., the original array is unchanged.
Well, this is because ArrayList resulting from Arrays.asList() is not of the type java.util.ArrayList.
Arrays.asList() creates an ArrayList of type java.util.Arrays$ArrayList which does not extend java.util.ArrayList, but only extends java.util.AbstractList.
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
In this case, list1 is of type ArrayList.
List<Integer> list2 = Arrays.asList(ia);
Here, the list is returned as a List view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2.
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
Here, you are creating a new ArrayList. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:
ArrayList list1 = (ArrayList)Arrays.asList(ia);
First of all, the Arrays class is a utility class which contains a number of utility methods to operate on Arrays (thanks to the Arrays class. Otherwise, we would have needed to create our own methods to act on Array objects)
asList() method:
asList method is one of the utility methods of Array class, it is a static method that's why we can call this method by its class name (like Arrays.asList(T...a) )
Now here is the twist. Please note that this method doesn't create new ArrayList object. It just returns a List reference to an existing Array object (so now after using asList method, two references to existing Array object gets created)
and this is the reason. All methods that operate on List object, may not work on this Array object using the List reference. Like
for example, Arrays size is fixed in length, hence you obviously can not add or remove elements from Array object using this List reference (like list.add(10) or list.remove(10);. Else it will throw UnsupportedOperationException).
any change you are doing using a list reference will be reflected in the exiting Arrays object (as you are operating on an existing Array object by using a list reference)
In the first case, you are creating a new Arraylist object (in the second case, only a reference to existing Array object is created, but not a new ArrayList object), so now there are two different objects. One is the Array object and another is the ArrayList object and there isn't any connection between them (so changes in one object will not be reflected/affected in another object (that is, in case 2, Array and Arraylist are two different objects)
Case 1:
Integer [] ia = {1,2,3,4};
System.out.println("Array : "+Arrays.toString(ia));
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); // new ArrayList object is created , no connection between existing Array Object
list1.add(5);
list1.add(6);
list1.remove(0);
list1.remove(0);
System.out.println("list1: " + list1);
System.out.println("Array: " + Arrays.toString(ia));
Case 2:
Integer [] ia = {1,2,3,4};
System.out.println("Array: " + Arrays.toString(ia));
List<Integer> list2 = Arrays.asList(ia); // Creates only a (new) List reference to the existing Array object (and NOT a new ArrayList Object)
// list2.add(5); // It will throw java.lang.UnsupportedOperationException - invalid operation (as Array size is fixed)
list2.set(0,10); // Making changes in the existing Array object using the List reference - valid
list2.set(1,11);
ia[2]=12; // Making changes in the existing Array object using the Array reference - valid
System.out.println("list2: " + list2);
System.out.println("Array: " + Arrays.toString(ia));
An explanation with documentation references would be better for someone looking for answer.
1. java.util.Arrays
This is a utility class with bunch of static methods to operate on given array
asList is one such static method that takes input array and returns an object of java.util.Arrays.ArrayList which is a static nested class that extends AbstractList<E> which in turn implements List interface.
So Arrays.asList(inarray) returns a List wrapper around the input array, but this wrapper is java.util.Arrays.ArrayList and not java.util.ArrayList and it refers to the same array, so adding more elements to the List wrapped array would affect the original one too and also we cannot change the length.
2. java.util.ArrayList
ArrayList has a bunch of overloaded constructors
public ArrayList() - // Returns arraylist with default capacity 10
public ArrayList(Collection<? extends E> c)
public ArrayList(int initialCapacity)
So when we pass the Arrays.asList returned object, i.e., List(AbstractList) to the second constructor above, it will create a new dynamic array (this array size increases as we add more elements than its capacity and also the new elements will not affect the original array) shallow copying the original array (shallow copy means it copies over the references only and does not create a new set of same objects as in original array)
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> namesList = Arrays.asList(names);
or
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> temp = Arrays.asList(names);
The above statement adds the wrapper on the input array. So the methods like add and remove will not be applicable on the list reference object 'namesList'.
If you try to add an element in the existing array/list then you will get "Exception in thread "main" java.lang.UnsupportedOperationException".
The above operation is readonly or viewonly.
We can not perform add or remove operation in list object.
But
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.ArrayList<String> list1 = new ArrayList<>(Arrays.asList(names));
or
String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> listObject = Arrays.asList(names);
java.util.ArrayList<String> list1 = new ArrayList<>(listObject);
In the above statement you have created a concrete instance of an ArrayList class and passed a list as a parameter.
In this case, methods add and remove will work properly as both methods are from ArrayList class, so here we won't get any UnSupportedOperationException.
Changes made in the Arraylist object (method add or remove an element in/from an arraylist) will get not reflect in to the original java.util.List object.
String names[] = new String[] {
"Avinash",
"Amol",
"John",
"Peter"
};
java.util.List < String > listObject = Arrays.asList(names);
java.util.ArrayList < String > list1 = new ArrayList < > (listObject);
for (String string: list1) {
System.out.print(" " + string);
}
list1.add("Alex"); // Added without any exception
list1.remove("Avinash"); // Added without any exception will not make any changes in original list in this case temp object.
for (String string: list1) {
System.out.print(" " + string);
}
String existingNames[] = new String[] {
"Avinash",
"Amol",
"John",
"Peter"
};
java.util.List < String > namesList = Arrays.asList(names);
namesList.add("Bob"); // UnsupportedOperationException occur
namesList.remove("Avinash"); // UnsupportedOperationException
Note that, in Java 8, 'ia' above must be Integer[] and not int[]. Arrays.asList() of an int array returns a list with a single element. When using the OP's code snippet, the compiler will catch the issue, but some methods (e.g., Collections.shuffle()) will silently fail to do what you expect.
Many people have answered the mechanical details already, but it's worth noting:
This is a poor design choice, by Java.
Java's asList method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add method, it throws an UnsupportedOperationException. This is unintuitive behavior! If a method says it returns a List, the standard expectation is that it returns an object which supports the methods of interface List. A developer shouldn't have to memorize which of the umpteen util.List methods create Lists that don't actually support all the List methods.
If they had named the method asImmutableList, it would make sense. Or if they just had the method return an actual List (and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the principle of least astonishment and the good object-oriented practice of avoiding UnsupportedOperationExceptions.
(Also, the designers might have made a interface ImmutableList, to avoid a plethora of UnsupportedOperationExceptions.)
package com.copy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class CopyArray {
public static void main(String[] args) {
List<Integer> list1, list2 = null;
Integer[] intarr = { 3, 4, 2, 1 };
list1 = new ArrayList<Integer>(Arrays.asList(intarr));
list1.add(30);
list2 = Arrays.asList(intarr);
// list2.add(40); Here, we can't modify the existing list,because it's a wrapper
System.out.println("List1");
Iterator<Integer> itr1 = list1.iterator();
while (itr1.hasNext()) {
System.out.println(itr1.next());
}
System.out.println("List2");
Iterator<Integer> itr2 = list2.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
Arrays.asList()
This method returns its own implementation of List. It takes an array as an argument and builds methods and attributes on top of it, since it is not copying any data from an array but using the original array this causes alteration in original array when you modify list returned by the Arrays.asList() method.
On the other hand, ArrayList(Arrays.asList());
is a constructor of ArrayList class which takes a list as argument and returns an ArrayList that is independent of list, i.e., Arrays.asList() in this case passed as an argument.
That is why you see these results.
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
2.List<Integer> list2 = Arrays.asList(ia);
In line 2, Arrays.asList(ia) returns a List reference of inner class object defined within Arrays, which is also called ArrayList but is private and only extends AbstractList. This means what returned from Arrays.asList(ia) is a class object different from what you get from new ArrayList<Integer>.
You cannot use some operations to line 2 because the inner private class within Arrays does not provide those methods.
Take a look at this link and see what you can do with the private inner class:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.ArrayList
Line 1 creates a new ArrayList object copying elements from what you get from line 2. So you can do whatever you want since java.util.ArrayList provides all those methods.
In response to some comments asking questions about the behaviour of Arrays.asList() since Java 8:
int[] arr1 = {1,2,3};
/*
Arrays are objects in Java, internally int[] will be represented by
an Integer Array object which when printed on console shall output
a pattern such as
[I#address for 1-dim int array,
[[I#address for 2-dim int array,
[[F#address for 2-dim float array etc.
*/
System.out.println(Arrays.asList(arr1));
/*
The line below results in Compile time error as Arrays.asList(int[] array)
returns List<int[]>. The returned list contains only one element
and that is the int[] {1,2,3}
*/
// List<Integer> list1 = Arrays.asList(arr1);
/*
Arrays.asList(arr1) is Arrays$ArrayList object whose only element is int[] array
so the line below prints [[I#...], where [I#... is the array object.
*/
System.out.println(Arrays.asList(arr1));
/*
This prints [I#..., the actual array object stored as single element
in the Arrays$ArrayList object.
*/
System.out.println(Arrays.asList(arr1).get(0));
// prints the contents of array [1,2,3]
System.out.println(Arrays.toString(Arrays.asList(arr1).get(0)));
Integer[] arr2 = {1,2,3};
/*
Arrays.asList(arr) is Arrays$ArrayList object which is
a wrapper list object containing three elements 1,2,3.
Technically, it is pointing to the original Integer[] array
*/
List<Integer> list2 = Arrays.asList(arr2);
// prints the contents of list [1,2,3]
System.out.println(list2);
Summary of the difference -
When a list is created without using the new, the operator Arrays.asList() method returns a wrapper which means:
you can perform an add/update operation.
the changes done in the original array will be reflected to List as well and vice versa.

Processing language: Get inner array values from ArrayList()

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]

Categories