Меню

List add java ошибка

Contents

  • 1 What is a fixed-length object?
  • 2 Example
  • 3 So, How to fix this UnsupportedOperationException?

If you are getting an UnsupportedOperationException while adding an object to List the reason could be that you are performing this operation on a fixed-size List object.

What is a fixed-length object?

You must have used Arrays.asList method to convert an array object to List object. If you closely look at the documentation of Arrays.asList method, it says that, Arrays.asList method returns a fixed-size list backed by the specified array, which means that the returned List is of a fixed size. You cannot change the structure as you do to a normal List. That is, you cannot add or remove elements to this List. This List object has a direct relation with the array from which it is created. Any change you make to the object within the List will get updated within the array also. Similarly, any change you make to the array object will get reflected in the List object as well.

Example

Below example will result in UnsupportedOperationException as it is trying to add new element to a fixed-size List object.

package com.techstackjournal;

import java.util.Arrays;
import java.util.List;

public class ArrayToList {

	public static void main(String[] args) {

		String[] arr = { "Alpha", "Beta", "Gamma" };

		List<String> list = Arrays.asList(arr);

		list.add("Theta");

		for (Object object : list) {
			System.out.println(object);
		}

	}

}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.add(AbstractList.java:153)
	at java.base/java.util.AbstractList.add(AbstractList.java:111)
	at com.techstackjournal.ArrayToList.main(ArrayToList.java:14)

So, How to fix this UnsupportedOperationException?

If your objective is to copy elements from array to List and add further elements to the List, then the approach to copy the elements from array to List using Arrays.asList is not correct. You should better go for other alternative approaches, which I explained in my “How to Convert an Array to List in Java?” post.

Scenario
Convert an array to a List using asList method of java.util.Arrays class.
Try to add an element to the list returned(by calling add method) or remove an element from the list(using remove method) and you will get an exception something like

Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at TestList.main(TestList.java:15)

Code to reproduce the above error is as below

// create an array
Long[] array = {1l,2l};
//convert it to list
List list = Arrays.asList(array);
// add to list. This throws error
list.add(3L);

Reason

asList method of java.util.Arrays class returns an object of a java ArrayList which is nested inside the class java.util.Arrays.

ArrayList extends java.util.AbstractList and it does not implement add or remove method.
Thus, when these methods are called on this list object, it calls add or remove method of java.util.AbstractList class which in turn throws java.lang.UnsupportedOperationException.

From java docs of add method of java.util.AbstractList class

throws UnsupportedOperationException if the add operation is not supported by this list

Secondly, the list returned by asList method of java.util.Arrays class is a fixed-size list which means that elements cannot be added to or removed from the list. Java docs of asList method states

Returns a fixed-size list backed by the specified array

If you look at the type of object returned by Arrays.asList method, it is Arrays$ArrayList<E>.

Solution
Our ultimate goal is to create an ArrayList which has the contents of the array and which also supports add and remove operations over it.

There are a couple of ways to do it as follows:
Method 1 : Iterating over the array

This method is an inefficient method which involves creating a new ArrayList, iterating over the array and in every iteration adding the element of the array to the list.
Code is given below.

Long[] array = { 1l, 2l };
// create a new empty list
List newList = new ArrayList();
//iterate over array
for (int i = 0; i < array.length; i++) {
  Long element = array[i];
  //add array element to list
  newList.add(element);
}
System.out.println(newList);

Output
Above code produces the following output

[1, 2, 3]

Method 2 : Creating an ArrayList directly with the contents of array

java.util.ArrayList has a constructor which takes another collection as argument.
Create a List using Arrays.asList method as you were using earlier and pass the resultant List to create a new ArrayList object.
This approach should be preferable over the first approach.

Long[] array={1l,2l};
//convert it to list
List list = Arrays.asList(array);
//create a new list with the contents of the above list
List newList = new ArrayList(list);
// add to list
newList.add(3L);
System.out.println(newList);

Output
Above code produces the following output

[1, 2, 3]

Let’s tweak in

  1. Any data structure which extends java.util.Collection interface can be supplied while creating a new ArrayList.
    Thus, objects of type java.util.Set such as HashSet, LinkedHashSet, objects of type java.util.List such as LinkedList, Vector can be used.
  2. An ArrayList uses an array behind the scenes.
  3. The type of ArrayList should be the same as that of the List supplied to it in the constructor.
  4. Though this post uses an ArrayList of type java.lang.Long but it is applicable to list of all types such as java.lang.String, java.lang.Integer etc.

Hit the clap if the article was helpful.

I am afraid there is a bit more wrong with your code than just that one error. As has been pointed out many times, you are trying to add an iterable collection of strings, number to your Array rather than n2 which is the iteration variable. If you want to add complete Collection instances you can do so using addAll().

As for the rest, I strongly recommend sticking to the Java naming convention and using lower case names for your variables. This will improve readability as many members of the community stick with that convention. You can find a neat write-up here.

You also seem to, unless your code is highly simplified, make the mistake of declaring an ArrayList inside the scope of a loop. you are instantiating a new ArrayList every time you enter the loop. I am not sure that is what you want to do. Be sure to check your design.

Also, if you simply want to avoid having duplicate values, I would suggest using Set as it performs the check automatically using the hashCode() of each member on insertion to check for collisions. Try doing:

HashSet<String> uniqueSet = new HashSet<>(number);

You should now have a Collection of unique strings.

I am afraid there is a bit more wrong with your code than just that one error. As has been pointed out many times, you are trying to add an iterable collection of strings, number to your Array rather than n2 which is the iteration variable. If you want to add complete Collection instances you can do so using addAll().

As for the rest, I strongly recommend sticking to the Java naming convention and using lower case names for your variables. This will improve readability as many members of the community stick with that convention. You can find a neat write-up here.

You also seem to, unless your code is highly simplified, make the mistake of declaring an ArrayList inside the scope of a loop. you are instantiating a new ArrayList every time you enter the loop. I am not sure that is what you want to do. Be sure to check your design.

Also, if you simply want to avoid having duplicate values, I would suggest using Set as it performs the check automatically using the hashCode() of each member on insertion to check for collisions. Try doing:

HashSet<String> uniqueSet = new HashSet<>(number);

You should now have a Collection of unique strings.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Lisp ошибка лишняя закрывающая скобка на входе
  • Lion alcolmeter sd 400 ошибка e bl