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.
Related
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:
Initialize Java Generic Array of Type Generic
(2 answers)
Closed 7 years ago.
What's syntax for creating an array of Objects of some class type?
Object<SomeClassType<T>>[] array?
Creating an array of a generic type is not allowed, but what you can do, is creating one with wildcard and casting it. The cast will give you a warning, but as the array only contains nulls by default, it can be done safely.
#SuppressWarnings("unchecked")
Object<SomeClassType<T>>[] array = (Object<SomeClassType<T>>[]) new Object<?>[length]
A number of ways to declare an array of objects of some class type. For example,
1. MyClass[] myArray = new MyClass[# of elements];
Then initialize each as, myArray[0] = new MyClass();, myArray[1] = new MyClass(), etc..
or via a for-loop
2. MyClass[] myArray = {new MyClass(), new MyClass(), ...};
I would say something like this would allow you to create an array.
String[] testArray = new String[3];
testArray[0] = "one";
testArray[1] = "two";
testArray[2] = "three";
String[] testArray = {"one","two","three"};
This question already has answers here:
Convert ArrayList<String> to String[] array [duplicate]
(6 answers)
Convert list to array in Java [duplicate]
(11 answers)
Closed 9 years ago.
List<String> list = getNames();//this returns a list of names(String).
String[] names = (String[]) list.toArray(); // throws class cast exception.
I don't understand why ? Any solution, explanation is appreciated.
This is because the parameterless toArray produces an array of Objects. You need to call the overload which takes the output array as the parameter, and pass an array of Strings, like this:
String[] names = (String[]) list.toArray(new String[list.size()]);
In Java 5 or newer you can drop the cast.
String[] names = list.toArray(new String[list.size()]);
You are attempting to cast from a class of Object[]. The class itself is an array of type Object. You would have to cast individually, one-by-one, adding the elements to a new array.
Or you could use the method already implemented for that, by doing this:
list.toArray(new String[list.size()]);
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());.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?
You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);
You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);
Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.
If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.