This question already has answers here:
make arrayList.toArray() return more specific types
(6 answers)
Closed 6 years ago.
Why does the code compile when I'm turning an ArrayList to an objectArray and does NOT compile when I'm turning an ArrayList to an stringArray (just if I mention "new String[0]")???
public static void main(String args[]) {
List<String> list = new ArrayList<>();
list.add("George");
list.add("John");
Object[] objectArray = list.toArray();
System.out.println(java.util.Arrays.toString(objectArray));
String[] stringArray = list.toArray(new String[0]);
System.out.println(java.util.Arrays.toString(objectArray));
}
To make it short, here are the signature of both methods for java.util.List
Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
So this is logic to get an error if you tried to store an Object[] into a String[]
You need to pass an array to specify the type. You should set the length directly, the methods can do it but you will do it easily
new String[list.length]
Related
This question already has answers here:
Converting array to list in Java
(24 answers)
Closed 9 months ago.
So I am trying to convert an (primitive) int array to a List,
for(int i=0;i<limit;i++) {
arr[i]=sc.nextInt();
}
List list=Arrays.asList(arr);
System.out.print(list);
Doing this so prints values like this for example, [[I#59a6e353] . There is an option to add <Integer> before variable list but since the array is primitive int, it could not.
Is there any solution for this? Adding <int[]> before variable list isn't an option as I need to call a bounded wildcard method.
Arrays.asList(arr) does not creates a List<Integer> but a List<int[]> with a single element (your arr).
You have to declare your variable as Integer[] arr if you have to use 'Arrays.asList'.
The signature of method Arrays.asList is the following one:
public static <T> List<T> asList(T... a);
You can see that it needs an array of generics T in input.
Therefore you can pass an array of Integer and it works. Example:
List<Integer> list= Arrays.asList(new Integer[] {1,2,3,4});
System.out.print(list);
Output:
[1, 2, 3, 4]
If you pass int[] you can have just a List<int[]> because int is a primitive type and it cannot be used as generic. Example:
List<int[]> list= Arrays.asList(new int[] {1,2,3,4});
System.out.print(list);
Output:
[[I#6b1274d2]
I suggest you to read the answer in this question.
This question already has answers here:
Array initialization syntax when not in a declaration
(4 answers)
Closed 3 years ago.
public class ListFile {
public static void main(String[] args){
String[] arr = {"text", "tekl"};
List<String> list = Arrays.asList(arr);
List<String> listt = Arrays.asList({"text", "tttt"});
}
}
Line 4 is totally working fine. However, line 5 gives error: "Syntax error on token ".", # expected after this token" at column 36.
Is the argument passed as {"text", "tttt"} is considered as block here?
When you do Type[] arr = { …, … }; that's an array initializer. It can only be used in array declarations (or in array creation expressions, i.e. new String[]{"a", "b"}).
Arrays.asList is defined to take varargs arguments (asList(T... a)), so you do not have to wrap your arguments in an array first: Arrays.asList("text", "tek1") will already implicitely create an array from your arguments and pass this to the method.
You are mixing possible correct synthax. These are the possibilities you want to specify:
List<String> listt = Arrays.asList("text", "tttt");
or
List<String> listt = Arrays.asList(new String[]{"text", "tttt"});
You try to insert something invalid in Arrays.asList.
Try to use
List<String> listt = Arrays.asList("text", "tttt");
From Java 8 javadocs
asList
#SafeVarargs
public static List asList(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts
as bridge between array-based and collection-based APIs, in
combination with Collection.toArray(). The returned list is
serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List stooges = Arrays.asList("Larry", "Moe", "Curly");
Type Parameters:
T - the class of the objects in the array
Parameters:
a - the array by which the list will be backed
Returns:
a list view of the specified array
This question already has answers here:
Converting array to list in Java
(24 answers)
How to convert an Array to a Set in Java
(19 answers)
Closed 3 years ago.
I am trying to get a String Collection in my Java code, so i'm trying something like this:
Collection c = new String[]{};
But i get this error: incompatible types: String[] cannot be converted to Collection.
Is there a way to convert String[] into Collection without doing something like this:
var array = new String[]{"Apple", "Banana"};
var arrayList = new ArrayList<String>();
for (String fruit : array) {
arrayList.add(fruit);
}
Collection c = arrayList;
Depends on the Collection. For example, if you want a List, use Arrays::asList
List<String> list = Arrays.asList(array);
or as a Collection:
Collection<String> list = Arrays.asList(array);
Be aware that this does not return a new List. It returns a fixed size view of the array you pass to the method, meaning that if the array changes, so does the list and vice versa. You cannot, however, change the length of the list.
There is no method for transforming an Array into a Set, but you can, for example, use a stream to achieve this:
Set<String> set = Arrays.stream(array).collect(Collectors.toSet());
Arrays are not Collections.
You will need to convert.
https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html
Arrays.asList(yourStringArray)
Java 8+
String[] arr = { "A", "B", "C", "D" };
List<String> list = Arrays.stream(arr).collect(Collectors.toList());
This question already has answers here:
Can I pass an array as arguments to a method with variable arguments in Java?
(5 answers)
Closed 7 years ago.
I have the following code snippet, which I can't understand why doesn't work:
List<Object[]> listOfObjectArrays;
listOfObjectArrays = new ArrayList<>();
Object[] objectArray = new Object[] {1, "two", null};
listOfObjectArrays.add(objectArray);
// works just fine
listOfObjectArrays = Arrays.asList(objectArray, objectArray);
// works just fine
listOfObjectArrays = Arrays.asList(objectArray); // *
// compile error: Incompatible types. Required: List<java.lang.Object[]> Found: List<java.lang.Object>
listOfObjectArrays = Arrays.asList(new Object[] {1, "two", null});
// compile error: Incompatible types. Required: List<java.lang.Object[]> Found: List<java.lang.Object>
Could somebody please point me in the right direction?
I already saw Jon Skeet's answer on an other question, but the last example there does not work for me. Even if I add a cast to either Object or Object[] in the line marked with * I get a compile error.
You can always tell Java that you want a list of Object[] by specifying the type parameter explicitly:
Object[] objectArray = { 1, "two", null };
List<Object[]> listOfObjectArrays = Arrays.<Object[]>asList(objectArray);
List<Object[]> listOfObjectArrays;
listOfObjectArrays = new ArrayList<>();
Object[][] objectArray = new Object[][] {{1, "two", null}};
listOfObjectArrays.add(objectArray[0]);
// works just fine
listOfObjectArrays = Arrays.asList(objectArray);
// works just fine
You need to do this. Your list contains Object[], when you do Arrays.asList it basically just iterates over the array and adds every index to the list.
Like:
List<T> list = new List<>();
for (Object obj : objectArray) {
list.add(obj);
}
After this it returns the list. As you can see it will return List, but you require List
Keppil nicely formulated a line that would solve my current problem, but Kevin's answer pointed me in the right direction to understand the situation.
Until now I used the abstraction that Arrays.asList() wraps the argument(s) in an array regardless of content and then uses it to create an ArrayList. According to this model my call should have resulted in an ArrayList backed by an array containing the passed Object[] parameter.
Looking at the Arrays.asList() source it became clear that my call (listOfObjectArrays = Arrays.asList(objectArray);) would have resulted in a List backed by objectArray itself, creating an ArrayList<Object>. So in order to have a list of Object[] arrays, I'd need to pass an array of Object[] arrays (as Kevin suggested), or explicitly set the type parameter of Arrays to Object[], forcing Arrays.asList() to interpret the argument as an array consisting of Object[] items (as per Keppil).
This question already has answers here:
Converting ArrayList to Array in java
(12 answers)
Closed 9 years ago.
I need to convert an array list of object type into a normal arrays.
ArrayList<object> list = new ArrayList<Object>();
list.add(4);
list.add(56);
list.add("two");
What is the easiest way to do this?
how can we change an existing array to an arraylist?
String st[]=new String[];
Integer in[]=new Integer[];
how can i convert this array into an array list of Object type so i can have both this arrays in one arraylist?
Suppose arrlist is an ArrayList. To convert it into array,try the follwing code.
Integer list[] = new Integer[arrlist.size()]; //arrlist is an ArrayList
list = arrlist.toArray(list2);
FOr more detailed example try this tutorial :
toArray method usage
Try,
Integer[] arr= list.toArray(new Integer[list.size()]);
You can use toArray()
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(4);
list.add(56);
Integer[] arr=list.toArray(new Integer[list.size()]);
Try this:
import org.apache.commons.lang.ArrayUtils;
int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]))
This approach will make two complete copies of the sequence: one Integer[] created by toArray, and one int[] created inside toPrimitive
arraylist can be converted into array using toArray() mehod in java.
Check
http://coderspoint.com/index.php?topic=7.msg10#msg10