This question already has answers here:
Converting an array of objects to an array of their primitive types
(9 answers)
Closed 4 years ago.
I have an ArrayList of type Boolean that requires to be manipulated as a boolean[] as I am trying to use:
AlertDialog builder;
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { ... });
However, while I can create a Boolean object array, I cannot find an efficient way to covert this object array to a primitive array that the builder function calls for (the only method I can come up with is to iterate over the Object array and build a new primitive array).
I am retrieving my Object array from the ArrayList as follows:
final Boolean[] checkedItems = getBoolList().toArray(new Boolean[getBoolList().size()]);
Is there something I can do with my ArrayList? Or is there an obvious casting/conversion method that I am missing??
Any help appreciated!
You aren't missing anything, the only way to do it is to Iterate over the list I'm afraid
An (Untested) Example:
private boolean[] toPrimitiveArray(final List<Boolean> booleanList) {
final boolean[] primitives = new boolean[booleanList.size()];
int index = 0;
for (Boolean object : booleanList) {
primitives[index++] = object;
}
return primitives;
}
Edit (as per Stephen C's comment):
Or you can use a third party util such as Apache Commons ArrayUtils:
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html
Using Guava, you can do boolean[] array = Booleans.toArray(getBoolList());.
Related
This question already has answers here:
How can I find if my ArrayList of int[] contains an int[]
(4 answers)
Check if ArrayList contains an Array Object
(1 answer)
The best way to check if List<String[]> contains a String[] [duplicate]
(4 answers)
Closed 3 years ago.
How do I check if an ArrayList<int[]> contains a given array [x, y]? I have found the same question in c#, but can't find any answers for java.
At the moment I am using myList.contains(myArray) but it is always evaluating to false, I assume for similar reasons as in C#. The solution in C# is to use LINQ, which does not exist in java.
Is there another way I can do this or will I have to write my own subroutine to pull out the values of each list element and compare them manually?
Edit: I've written my own subroutine to do this which works (assuming each array has two elements), but a more elegant solution would be appreciated
private boolean contains(List<int[]> list, int[] array) {
for (int[] listItem : list) {
if (listItem[0] == array[0] &&
listItem[1] == array[1]) {
return true;
}
}
return false;
The .contains method compares each object with .equals which as this answer points out just compares the identity of the array objects (i.e. checks if they're the same Java object), it does not compare the contents of the arrays.
What you need to do is to write a for loop, check each element with Arrays.equals(..) (which compares the contents of the arrays). For example:
boolean found = false;
for (int i = 0; i < myList.size(); i++)
if (Arrays.equals(myArray, myList.get(i)) found = true;
There is Arrays.equals, and also Streams, which are designed for similar use cases as LINQ. In this case, the Stream.anyMatch method is very similar to Any in LINQ.
Combining these two, you can write your method in one statement:
private boolean contains(List<int[]> list, int[] array) {
return list.stream()
.anyMatch(x -> Arrays.equals(x, array));
}
This question already has answers here:
make arrayList.toArray() return more specific types
(6 answers)
Closed 4 years ago.
The method I have is supposed to return a String [] so i used toArray method. But I get error regarding object cannot be converted to strings. I have initialized the list as String as well and am unable to figure out the error that I am getting. Everywhere I read, they say initialize as String and I have already done that. how can I fix it??
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
.......(job done)
return c.toArray();
--The entire code:
public static String[] anagrams(String [] a) {
ArrayList<String> b = new ArrayList<String>(Arrays.asList(a));
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
int l=a.length;
int i,j;
for (i=0;i<l;i++) {
for (j=i+1;j<l;j++) {
if (check(b.get(i),b.get(j))){
if (c.contains(b.get(j)))
c.remove(j);
}
}
}
return c.toArray();
}
Tryy this
return c.toArray(new String[c.size()]);
This basically initializes size of the array
There are two toArray methods in an ArrayList. From the docs:
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.
Right now you are using the first version, which returns an Object array. Since you want a String array, not an Object array, you must use the second version:
return c.toArray(new String[0]);
The array parameter is needed so ArrayList knows which type to return. If you provide an empty array, ArrayList will allocate a new array for the desired type. However you can also provide an array that is big enough for all elements of the list, then ArrayList will use that array instead of initializing a new one:
return c.toArray(new String[c.size()]);
This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 5 years ago.
I want to know what kinds of reference can be array elements.
I know that there're primitive types like:
String[] strs = new String[5];
But there is no
List<String>[] stringList;
However, when I new a class, there is
Class Student{
String name;
List<String> courses;
}
Student[] students = new Student[5];
It says "The element type of an array may be any type, whether primitive or reference."
I think Student is reference and List<> is also reference. What's the difference between them?
Thanks.
Anything can go in an array. Primitives, other arrays, or lists.
Any of the following are legitimate declarations:
int[] intArray;
int[][] arrayOfIntArrays;
List <String> stringList;
List <String[]> stringArrayList;
List <List<String[]>> badIdea; //list of a list of string arrays
List<String>[] array of a list of strings
etc.
An array is a subclass of Object. There is nothing special about it except that java gave it some unique syntax. Otherwise, it's just like anything else you run into in java.
This question already has answers here:
Create a List of primitive int?
(12 answers)
Closed 8 years ago.
In my Java program, I want to store a list of primitive values. I could do something like this:
int x = 0;
double timestamp = 123.1d;
List<Object> data = new ArrayList<Object>();
data.add(x);
data.add(timestamp);
But then the problem is that I do not know exactly what kind of objects i store in the list. So is there any better way to do that?
Well, Double, Integer, Long all belong to the Number-class. So a
List<Number>
would probably fit. It is exactly what it is - a List of numbers of unspecified subtype. Because of autoboxing you should be able to just add the primitives, but the better practice would be to use the Wrapper-classes.
The Number-class offers methods to get the different representations of the Number, for example doubleValue(). So you could convert all the values in the List<Number> to (as an example) Doubles by using this method. For more reference see the Oracle documentation for Number.
You could use List<Object> and add any kind of object to it.While retrieving the Object back from List<Object> you can get class of object by list.get(0).getClass() or you could check for list.get(i) instacne of Double.
use wrapper class and use instance of operator to check datatype of value.
like
Integer x = 0;
Double timestamp = 123.1d;
List<Object> data = new ArrayList<Object>();
data.add(x);
data.add(timestamp);
if(data.get(0) instance of Integer)
{
...
}
else if(data.get(0) instance of Double )
{
..
}
This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 9 years ago.
Is there a way, to convert a List of Integers to Array of ints (not integer). Something like List to int []? Without looping through the list and manually converting the intger to int.
You can use the toArray to get an array of Integers, ArrayUtils from the apache commons to convert it to an int[].
List<Integer> integerList = new ArrayList<Integer>();
Integer[] integerArray = integerList.toArray(new Integer[0]);
int[] intArray = ArrayUtils.toPrimitive(integerArray);
Resources :
Apache commons - ArrayUtils.toPrimitive(Integer[])
Apache commons lang
Javadoc - Collection.toArray(T[])
On the same topic :
How to convert List to int[] in Java?
I'm sure you can find something in a third-party library, but I don't believe there's anything built into the Java standard libraries.
I suggest you just write a utility function to do it, unless you need lots of similar functionality (in which case it would be worth finding the relevant 3rd party library). Note that you'll need to work out what to do with a null reference in the list, which clearly can't be represented accurately in the int array.
No :)
You need to iterate through the list. It shouldn't be too painful.
Here is a utility method that converts a Collection of Integers to an array of ints. If the input is null, null is returned. If the input contains any null values, a defensive copy is created, stripping all null values from it. The original collection is left unchanged.
public static int[] toIntArray(final Collection<Integer> data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection<Integer> effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList<Integer>(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
Update: Guava has a one-liner for this functionality:
int[] array = Ints.toArray(data);
Reference:
Ints.toArray(Collection<Integer>)
List<Integer> listInt = new ArrayList<Integer>();
StringBuffer strBuffer = new StringBuffer();
for(Object o:listInt){
strBuffer.append(o);
}
int [] arrayInt = new int[]{Integer.parseInt(strBuffer.toString())};
I think this should solve your problem