removeIf() of List is not working as intended [duplicate] - java

This question already has an answer here:
java.util.Arrays.asList when used with removeIf throws UnsupportedOperationException
(1 answer)
Closed 4 years ago.
Whenever I try to remove an element from a List using list.removeIf(condition) it throws UnsupportedOperationException:
public class Test
{
public static void main(final String[] args)
{
String[] stringArray = new String[]{"A","B","C","D"};
List<String> stringList = Arrays.asList(stringArray);
stringList.forEach(System.out::println);
stringList.removeIf((String string) -> string.equals("B"));
stringList.forEach(System.out::println);
}
}
Why is it not working?

Arrays.asList returns a fixed sized List - backed by the array you pass in - so, just as you can't remove (or add) elements from an array, you can't remove (or add) elements from the List.
Use a java.util.ArrayList in order to be able to remove elements:
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));

Array.asList method returns an ArrayList of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classic java.util.ArrayList (resizable and item-removable)

Related

Unable to perform an operation on ArrayList [duplicate]

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;
}

System.out.println() is printing [S#123772c4 instead of actual string [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
I have the following code:
public static void closestInSubnet(int[][] adjlist, short[][] addrs, int src, short[][] queries) {
// TODO
List<String> address = ToList(addrs);
List<String> quer = ToList(queries);
for (String i : address) {
System.out.println(i);
}
}
public static List<String> ToList(short[][] preList) {
List<String> list = new ArrayList<String>();
for (short[] i : preList) {
list.add(i.toString());
}
return list;
}
I want it to be printing out the lists converted to Strings however I am getting the following in console:
[S#7637f22
[S#4926097b
[S#762efe5d
[S#5d22bbb7
[S#41a4555e
[S#3830f1c0
[S#39ed3c8d
[S#71dac704
[S#123772c4
I'm sure there is a quick fix for this any help would be great. thanks
You are created a list of arrays. You are now looping through the list and attempting to print the list in one go. What you are seeing is the object ID of the arrays.
You need to add an inner loop to print the individual elements of each array.

Create a list from instance variables of items in array using streams [duplicate]

This question already has answers here:
Create list of object from another using Java 8 Streams
(3 answers)
Java - A method that takes vararg and returns arraylist?
(2 answers)
Varargs to ArrayList problem in Java
(4 answers)
Closed 2 years ago.
I have an array of items, and I want to create a list (or any iterable) from an instance variable belonging to them.
public void foo(final MyClass... args) {
final List<Baz> properties = new ArrayList<>();
for (final MyClass a : args) {
properties.add(a.getProperty());
}
}
How would I do this using a one-liner stream?
List<Baz> list = Arrays.stream(args).map(MyClass::getProperty).collect(Collectors.toList());
Iterable<Baz> iterable = () -> Arrays.stream(args).map(MyClass::getProperty).iterator();
Assuming that getProperty() method of MyClass returns an object of type Baz
List<Baz> properties = Stream.of(args)
.map(myClazz -> myClazz.getProperty())
.collect(Collectors.toList())

Using set method on List<Integer> causes Unsupported Operation Exception [duplicate]

This question already has answers here:
CopiesList.addAll method throws UnsupportedOperationException
(2 answers)
Closed 3 years ago.
Im trying to create an 8 element list [0,0,0,0,0,0,0,0] and then change the value of given index using the .set method. However the code raises an exception.
import java.util.*;
public class HQ {
public static void main(String[] arg)
{
List<Integer> quantity= Collections.nCopies(8, 0);
quantity.set(0,1);
}
}
I thought it would change the first element of quantity to be 1 and leave the rest as 0.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.set(AbstractList.java:132)
at HQ.main(HQ.java:10)
Collections.nCopies will return immutable list, so you can't modify it
Returns an immutable list consisting of n copies of the specified object. The newly allocated data object is tiny (it contains a single reference to the data object). This method is useful in combination with the List.addAll method to grow lists. The returned list is serializable.
You can use stream to create mutable list with n copies
List<Integer> ints = IntStream.range(0, 7).map(i -> 0).boxed().collect(Collectors.toList());
or just convert immutable list into mutable
List<Integer> quantity1= Collections.nCopies(8, 0);
List<Integer> quantity = new ArrayList<Integer>(quantity1);

Incomparable object types --> Object to string? [duplicate]

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()]);

Categories

Resources