This question already has answers here:
How to create a generic array? [duplicate]
(4 answers)
How to create a generic array in Java?
(32 answers)
Closed 8 years ago.
I am working on a problem and I was provided with the following method header:
T[] getAll(T[] elements)
I am not allowed to modify it.
The purpose of the method is to fill the elements array with elements from a member list. Before this is done however we need to check if the array's capacity is large enough for all the elements to fit. If it is not we have to create a new array with an appropriate capacity.
How do I create an array when I do not know which datatype the elements are? As far as I know it's not possible to create generic arrays.
#Override
public T[] getAll(T[] elements)
{
// TODO create new array if needed
for(int i = 0; i < size(); i++)
{
elements[i] = list.element();
list.move();
}
return elements;
}
Related
This question already has answers here:
Why do I get an UnsupportedOperationException when trying to remove an element from a List?
(17 answers)
java.lang.UnsupportedOperationException adding to a list [duplicate]
(2 answers)
Arrays.asList give UnsupportedOperationException [duplicate]
(2 answers)
UnsupportedOperationException at java.util.AbstractList.add
(7 answers)
Why i can't add element using list reference which returned by method [duplicate]
(3 answers)
Closed 1 year ago.
My intention is to make a shallow clone of the ArrayList but before that i am facing an issue while modifying the list.
Adding the another element in the list giving
UnsupportedOrderException
WHY?
class Mine implements Cloneable {
public List<Integer> list;
Mine(List<Integer> mylist) {
this.list = mylist;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Demo {
public static void main(String[] args) throws CloneNotSupportedException {
List<Integer> klist= Arrays.asList(10,20,30,40,50);
Mine m1=new Mine(klist);
m1.list.add(11); // <- why i am unable to add to the list
Mine m2= (Mine) m1.clone();
}
}
You cannot change the number of elements of the List (using add() or remove() or similar) returned by Arrays.asList (but it allows to change elements using .set()).
From the docs of Arrays.asList:
The returned list implements the optional Collection methods, except those that would change the size of the returned list. Those methods leave the list unchanged and throw UnsupportedOperationException.
Instead, you can create an ArrayList with the same elements:
List<Integer> klist= new ArrayList<>(Arrays.asList(10,20,30,40,50));
Arrays.asList() returns a List<T> implementation that is backed by the original array. (Changed to the array can be seen via the list and vice versa.)
Arrays have a fixed size in Java, therefore the list returned by Arrays.asList has to have a fixed size as well - you can't add to it, and you can't remove from it.
You can create a new ArrayList<T> instead, which creates a copy of the array:
List<Integer> list = new ArrayList<>(Arrays.asList(...));
Although ArrayList is still backed by an array, it will create a new array where necessary. The array is an implementation detail, rather than the list being a "view" over an existing array as is returned by Arrays.asList.
In addition to #dan1st's answer (and now #JonSkeet as well), you can create your own asList() method to return a mutable List<T>:
static public List<T> asMutableList(T ... elts) {
List<T> lst = new ArrayList<>(elts.length);
for (T el : elts) {
lst.add(el);
}
return lst;
}
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:
Sort a two dimensional array based on one column
(8 answers)
Closed 5 years ago.
Assume I have this 2D array:
array[0][] = {5,B,2}
array[1][] = {9,R,4}
array[2][] = {3,B,1}
array[3][] = {1,R,8}
How can I sort this array in such a way that this is the output:
array[0][] = {3,B,1}
array[1][] = {5,B,2}
array[2][] = {9,R,4}
array[3][] = {1,R,8}
Basically sorting them based on the [i][2] element.
This is how I declared the array:
String[][] splitnodes = new String[7][];
Is it even possible? If it is, how?
Thanks!
One approach would be to implement a "normal search" like insertion sort, where you only compare the second element, and then carry the rest of the elements
You can use any sorting tecnique and in the step involving the comparision you need to compare the 2nd element of each sub array. Using the utility method provided in the J0DK you may also use sortmethod defined in Arrays.java.
java.util.Arrays.sort(array, new
java.util.Comparator<String[]> () {
public int compare(String[] a, String[] b) {
return Integer.compare(Integer.parseInt( a[2]), Integer.parseInt(b[2]));
}
});
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 7 years ago.
I know I have done this in the past. I have an ArrayList that has been populated with integers. I need to iterate over it and find the maximum value. However, when I iterate over an array with something like this:
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) > max)
{
max = list.get(i);
}
}
I get an error that says java.lang.Object cannot be converted to int or that > is a bad operand type. I have never encountered this before, and I have used arraylists multiple times for this same purpose. What am I doing wrong here?
max is declared as an int but is not initialized.
Most likely you declared the ArrayList just like this:
ArrayList list = new ArrayList<>();
instead of :
ArrayList<Integer> list = new ArrayList<>();