ArrayList to a String Array - java

Given 3 variables (homeNumber,mobileNumber and workNumber), which can be null, but atleast one of those will be a String, I need to return a String array so I can use it later on an Android Dialog. I'm having troubles doing this. I tried doing it in an ArrayList and removing all null elements, which leaves an ArrayList with only Strings, like I want, but when trying to change it to an Array I get a ClassCast exception on the last line.
ArrayList numberList = new ArrayList();
numberList.add(homeNumber);
numberList.add(mobileNumber);
numberList.add(workNumber);
numberList.removeAll(Collections.singleton(null));
final String[] items= (String[]) numberList.toArray();
Any ideas how to fix this?

String[] items = new String[numberList.size()];
numberList.toArray(items);

You can do one of two things:
Pass in the type of array you want to get (there's no need to instantiate a full length array, performance is the same regardless):
final String[] items= (String[]) numberList.toArray(new String[0]);
However, the better solution is to use generics:
List<String> numberList = new ArrayList<String>();
final String[] items= (String[]) numberList.toArray();

The return type of ArrayList.toArray() is Object[], unless you pass an array as the first argument. In that case the return type has the same type as the passed array, and if the array is large enough it is used. Do this:
final String[] items= (String[])numberList.toArray(new String[3])

Use the other method toArray() of List class:
numberList.toArray(new String[numberList.size()]);

Change
ArrayList numberList = new ArrayList();
to
List<String> numberList = new ArrayList<String>();

Related

How do I add an array into an arraylist (so that it becomes a 2D arraylist) in java?

I have an array:
String[] a = {"abc","def","ghi"}
Now I want to store this array into my string arraylist
ArrayList<String> arr = new ArrayList<>();
so that it becomes like this:
[["abc","def","ghi"]]
I have tried this code but it doesn't work:
arr.add(Arrays.asList(a));
Please help me
Since Arrays.asList(a) returns List, to add it to your list you need to use addAll()
arr.addAll(Arrays.asList(a));
Instead of
arr.add(Arrays.asList(a));
But the result will be ["abc","def","ghi"]
If you want to achieve this [["abc","def","ghi"]] then define your ArrayList as
List<List<String>> arr = new ArrayList<>();
using arralist addAll() method we can do but,
Using arrayList is depricated approach , use Streams instead of it:
System.out.println(Collections.singletonList(Stream.of(new String[] {"abc","def","ghi"}).collect(Collectors.toList())));
will result in:
[[abc, def, ghi]]

Storing an ArrayList in an 2d Array Java

How can I store an ArrayList in a two dimensional array?
I've tried it like this, but it won't work:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];
but it won't even let me declare the ArrayList-Array.
Is there a way to store a list in a 2d array?
Thanks in advance!
You can't create arrays of generic types in Java. But this compiles:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;
Why can't you create these arrays? According to the Generics FAQ, because of this problem:
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal
Object[] objArr = intPairArr;
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed
Assuming you want an ArrayList inside an ArrayList inside yet another ArrayList, you can simply specify that in your type declaration:
ArrayList<ArrayList<ArrayList<Integer>>> foo = new ArrayList<ArrayList<ArrayList<Integer>>>();
Entries can be accessed via:
Integer myInt = foo.get(1).get(2).get(3);
Just be wary of boundaries - if you try to access an out of bounds index you'll see Exceptions thrown.

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!

Convert String results[] To ArrayList<String> alist; [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert String[] to ArrayList<String>
hi please can anyone help me I have :
private String results[];
private ArrayList<String> alist;
I want convert
String results[] to ArrayList<String>
Convert String Array to ArrayList as
String[] results = new String[] {"Java", "Android", "Hello"};
ArrayList<String> strlist =
new ArrayList<String>(Arrays.asList(results));
You can use the Arrays.asList() method to convert an array to a list.
E.g. List<String> alist = Arrays.asList(results);
Please note that Arrays.asList() returns a List instance, not an ArrayList instance. If you really need an ArrayList instance you can use to the ArrayList constuctor an pass the List instance to it.
Try this:
ArrayList<String> aList = new ArrayList<String>();
for(String s : results){
aList.add(s);
}
What this does is, it constructs an ArrayList of Strings called aList: ArrayList<String> aList = new ArrayList<String>();
And then, for every String in results: String s : results
It add's that string: aList.add(s);.
Hope this helps!
You should use
Arrays.asList(results)
by default, unless you absolutely for some reason must have an ArrayList.
For example, if you want to modify the list, in which case you use
new ArrayList(Arrays.asList(results))

Java Array and ArrayList

When I try to create an ArrayList myArrayList from an array, using Arrays.asList(myArray), I am not getting the List of elements in myArray. Instead I get list of Array.
The size of myArrayList is 1 . When I try to do myArrayList.toArray(), I am getting a two dimensional array. What to do to get the elements of myArray in a list? Is iterating the only option??
Firstly, the asList method is the right method:
Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected
The problem may be that you are calling the varargs asList method in such a way that java is interpreting your parameter as the first varargs value (and not as an array of values).
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]
To fix this problem, try casting your parameter as Object[] to force the varargs invocation, eg:
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
What is the type of myArray? You cannot use Arrays.asList with an array of primitive type (such as int[]). You need to use loop in that case.
There are different ways by which you can achieve it.3 example of converting array to arraylist and arraylist to array in java might help.
Would this work?
Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);
Try providing the generic type in the method call. The following gives me a list of 2 String elements.
String[] strings = new String[]{"1", "2"};
List<String> list = Arrays.<String>asList(strings);
System.out.println(list.size());

Categories