List add java ошибка

I am using Eclipse JUno ,I am having trouble with the .add() of the arraylist guys please help.here is my code

     import java.util.ArrayList;
public class A
{
public static void main(String[] args) 
  {
    ArrayList list=new ArrayList();
    list.add(90);
    list.add(9.9);
    list.add("abc");
    list.add(true);
    System.out.println(list);
  }
}

the error which is coming is :

 Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method add(int, Object) in the type ArrayList is not applicable for the arguments (int)
    The method add(Object) in the type ArrayList is not applicable for the arguments (double)
    The method add(Object) in the type ArrayList is not applicable for the arguments (boolean)

    at A.main(A.java:7)

but here is the weird thing ,that the line

  list.add("abc");

is not causing any error.. ADD method of list take one argument which is an object type then why i am facing this problem please help guys..i had searched a lot i did not get any solution.I have to do practice on this and due to this error i cant continue my practice..

kosa's user avatar

kosa

65.9k13 gold badges128 silver badges167 bronze badges

asked Jun 13, 2013 at 14:31

user2461414's user avatar

9

I suppose that you’re using java prior version 1.5. Autoboxing was introduced in java 1.5. And your code compiles fine on java 1.5+.

Compile as source 1.4:

javac -source 1.4 A.java


A.java:7: error: no suitable method found for add(int)
    list.add(90);
        ^
    method ArrayList.add(int,Object) is not applicable
      (actual and formal argument lists differ in length)
    method ArrayList.add(Object) is not applicable
      (actual argument int cannot be converted to Object by method invocation conversion)
A.java:8: error: no suitable method found for add(double)
    list.add(9.9);
        ^
    method ArrayList.add(int,Object) is not applicable
      (actual and formal argument lists differ in length)
    method ArrayList.add(Object) is not applicable
      (actual argument double cannot be converted to Object by method invocation conversion)
A.java:10: error: no suitable method found for add(boolean)
    list.add(true);
        ^
    method ArrayList.add(int,Object) is not applicable
      (actual and formal argument lists differ in length)
    method ArrayList.add(Object) is not applicable
      (actual argument boolean cannot be converted to Object by method invocation conversion)
3 errors

With 1.5 (or later):

javac -source 1.5 A.java

warning: [options] bootstrap class path not set in conjunction with -source 1.5
Note: A.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 warning

I suggest you to update your java or box all primitives to objects manually, as @SoulDZIN suggested.

answered Jun 13, 2013 at 14:41

Mikita Belahlazau's user avatar

0

Notice that the ‘add’ method is failing for the data types:

int, double, and boolean.

These are all primitive data types and not ‘Objects’, which the method is expecting. I believe that autoboxing is not occurring here because you are using literal values, I’m not sure about this though. Nevertheless, to fix this, use the associated Object type of each primitive:

ArrayList list=new ArrayList();
list.add(new Integer(90));
list.add(new Double(9.9));
list.add("abc");
list.add(new Boolean(true));
System.out.println(list);

SOURCE: Experience

EDIT:

I always try to specify the type of my Collection, even if it is an Object.

ArrayList<Object> list = new ArrayList<Object>();

However, apparently this isn’t a good practice if you are running Java 1.4 or less.

answered Jun 13, 2013 at 14:37

souldzin's user avatar

souldzinsouldzin

1,42811 silver badges23 bronze badges

2

Works great with JDK 6

public static void main(String[] args) {
            ArrayList list=new ArrayList();
            list.add(90);
            list.add(9.9);
            list.add("abc");
            list.add(true);
            System.out.println(list);
    }

Printed result :[90, 9.9, abc, true].

If still you are using lesser version than jdk 6.Please specify version.

answered Jun 13, 2013 at 14:41

Suresh Atta's user avatar

Suresh AttaSuresh Atta

120k37 gold badges196 silver badges305 bronze badges

0

Когда хотим добавить новый элемент в список, то мы сообщаем «что» хотим добавить и, если нужно, также указываем «куда» надо добавить.
Например,
ArrayList<String> list = new ArrayList<>();
list.add(«Hello»);
добавляет строку в конец списка, как ты уже знаешь.

Поэтому написав list.add(i); ты просто указываешь «куда» надо добавить новый элемент, а вот «что» добавить, ты не сообщаешь.

https://javarush.com/groups/posts/2354-arraylist-v-java

background

Want to add a set of dynamic strings to an array and implement the function of processing a string group in memory.

import java.util.List;
...
private List jarList;
...
jarList.add(file);
...

Refer to URL: https://docs.racle.com/javase/6/docs/api/java/util/list.html

Wrong

Cannot invoke "java.util.List.add(Object)" because "this.jarList" is null

reason

This error is because the method of initialization does not instantiate the List method, directly calls add (), must be instantified, trigger an empty pointer exception, and call the list method to achieve the expected goal

Solution

After fixing the ArrayList method, it is instantiated and resolved.

import java.util.ArrayList;
...
private ArrayList<File> jarList = new ArrayList<File>();
...
jarList.add(file);

I’m taking a Java class in College. My instructor is actually a teacher for languages derived from C, so she can’t figure out what’s going on with this piece of code. I read on this page http://docs.oracle.com/javase/6/docs/api/java/util/List.html that I could use the syntax «list[].add(int index, element)» to add specific objects or calculations into specific indexes, which reduced the amount of coding needed. The program I’m looking to create is a random stat generator for D&D, for practice. The method giving the error is below:

//StatGenrator is used with ActionListener

private String StatGenerator ()
{
        int finalStat;
        String returnStat;

        //Creates an empty list.
        int[] nums={};

        //Adds a random number from 1-6 to each list element.
        for (int i; i > 4; i++)
            nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class expected"

        //Sorts the list by decending order, then drops the
        //lowest number by adding the three highest numbers 
        //in the list.            
        Arrays.sort(nums);
        finalStat = nums[1] + nums[2] + nums[3]; 

        //Converts the integer into a string to set into a 
        //texbox.
        returnStat = finalStat.toString();
        return returnStat;
}

My end goal is to use some kind of sorted list or method of removing the lowest value in a set. The point of this method is to generate 4 random numbers from 1-6, then drop the lowest and add the three highest together. The final number is going to be the text of a textbox, so it is converted to a string and returned. The remainder of the code works correctly, I am only having trouble with this method.

If anyone has any ideas, I’m all ears. I’ve researched a bit and found something about using ArrayList to make a new List object, but I’m not sure on the syntax for it. As a final note, I tried looking for this syntax in another question, but I couldn’t find it anywhere on stackoverflow. Apologies if I missed something, somewhere.

Сегодня я писал статистику. Я случайно написал следующий фрагмент кода и запустил JUnit. Оказалось! ! ! Вызов метода list.add сообщит об ошибке (java.lang.UnsupportedOperationException)
Этот фрагмент кода выглядит следующим образом:

@Test
    public void test01() {

        List<String> a7DaysTitleList = Arrays.asList(«7   [0]»,"7-е [1]","7-е [2-10]",«7-е [10-30]»);
        // a7DaysTitleList = new ArrayList ({"7 [0]", «7 [1]», «7 [2-10]», «7 [10-30]»}); не существует!

        for (String str : a7DaysTitleList) {
            System.out.println(str);
        }

        a7DaysTitleList.add(«7   [30, + ∞)»);// Сообщаем об ошибке

        for (String str : a7DaysTitleList) {
            System.out.println(str);
        }

    }

График эффекта бега:

Ошибка: java.lang.UnsupportedOperationException в java.util.AbstractList.add (AbstractList.java:131) в java.util.AbstractList.add (AbstractList.java:91) в com.markin.test.ListTest.test01 (ListTest. java: 21) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в…

В чем дело, вызов add может сообщить об ошибке, вы можете увидеть сообщение об ошибке «исключение неподдерживаемой операции»!
Как видите, я использую Arrays.asList (xxx) для возврата списка. Может быть, в этом списке есть что-то особенное!
БоюсьВолна исходного кода, Иди ты:
Удерживая нажатой клавишу Ctrl, щелкните «Массивы».asList(Xxx) в исходный код класса Array (Array.class)! Примечание. Плагин декомпиляции прост в использовании! ! !
Array
Как видите, вызов статического метода asList (xxx) для Array возвращает ArrayList.
Погрузитесь глубже, удерживая Ctrl, щелкните ArrayList, суть здесь,

Я его не вижу, не вижу, имя файла богатое! (Серьезно, кашель — это знак доллара $), указывающий на то, что ArrayList является внутренним классом Array! (После того, как внутренний класс скомпилирован, это будет отдельный файл, формат именования: внешний класс + «знак доллара» + внутренний класс), ну посмотрите на это, отметьте его большой красной стрелкой,
private final E[] a;
Однако дело не в том, что окончательный измененный ссылочный тип является неизменяемой ссылкой, а в том, что содержимое должно быть изменяемым? ! (Это знание непонятно приветствуется приставанием)
Сравните метод добавления ArrayList и java.util.ArrayList внутри Array и найдите
ArrayList внутри массива не переписывал добавление (xxx) AbstractList, что заставляло нас вызывать добавление (xxx) кода апелляции, которое фактически напрямую вызывало добавление (xxx) класса AbstractList, поэтому оно было брошено напрямую Исключение UnsupportedOperationException.


Хорошо, я знаю, почему, что мне делать, послушно писать новый ArrayList (), добавлять один за другим, ха-ха

Я хотел использовать метод Collections.copy () для реализации копирования, но произошла ошибка. Collections.copy сообщил об ошибке: Источник не помещается в dest. Решение:http://stackoverflow.com/questions/6147650/java-lang-indexoutofboundsexception-source-does-not-fit-in-dest
В соответствии с подсказкой в ​​тексте: напрямую передать исходный список в метод построения нового списка
List dest = new ArrayList(source);

Сноска: Если вы столкнулись с проблемой, решите ее.


Уровень ограничен, если в эссе есть какие-либо ошибки или упущения, пожалуйста, дайте больше рекомендаций от всех экспертов.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The UnsupportedOperationException is one of the common exceptions that occur when we are working with some API of list implementation. It is thrown to indicate that the requested operation is not supported.

    This class is a member of the Java Collections Framework.

    All java errors implement the java.lang.Throwable interface or are inherited from another class. The hierarchy of this Exception is-

      java.lang.Object

             java.lang.Throwable

                       java.lang.Exception

                              java.lang.RuntimeException

                                      java.lang.UnsupportedOperationException

    Syntax:

    public class UnsupportedOperationException
    extends RuntimeException

    The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an 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 this method is called on the list object, it calls to add or remove method of AbstractList class which throws this exception. Moreover, the list returned by the asList method is a fixed-size list therefore it cannot be modified.

    The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object

    Java

    import java.util.Arrays;

    import java.util.List;

    public class Example {

        public static void main(String[] args)

        {

            String str[] = { "Apple", "Banana" };

            List<String> l = Arrays.asList(str);

            System.out.println(l);

            l.add("Mango");

        }

    }

    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 Example.main(Example.java:14)

    We can solve this problem by using a mutable List that can be modified such as an ArrayList. We create a List using Arrays.asList method as we were using earlier and pass that resultant List to create a new ArrayList object. 

    Java

    import java.util.ArrayList;

    import java.util.List;

    import java.util.*;

    public class Example {

        public static void main(String[] args) {

            String str[] = { "Apple", "Banana" };

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

            List<String> l = new ArrayList<>(list);

            l.add("Mango");

            for(String s: l )

              System.out.println(s);

        }

    }

    Last Updated :
    09 Mar, 2021

    Like Article

    Save Article

    Я использую Eclipse JUno, у меня возникают проблемы с .add() ребятами из arraylist, пожалуйста, помогите.здесь мой код

         import java.util.ArrayList;
    public class A
    {
    public static void main(String[] args) 
      {
        ArrayList list=new ArrayList();
        list.add(90);
        list.add(9.9);
        list.add("abc");
        list.add(true);
        System.out.println(list);
      }
    }
    

    ожидаемая ошибка:

     Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        The method add(int, Object) in the type ArrayList is not applicable for the arguments (int)
        The method add(Object) in the type ArrayList is not applicable for the arguments (double)
        The method add(Object) in the type ArrayList is not applicable for the arguments (boolean)
    
        at A.main(A.java:7)
    

    но вот что странно, что строка

      list.add("abc");
    

    не вызывает никакой ошибки. ADD метод списка принимает один аргумент, который является типом объекта, то почему я столкнулся с этой проблемой, пожалуйста, помогите парням.. я много искал, я не получал никакого решения. Мне нужно сделать практика по этому поводу и из-за этой ошибки я не могу продолжить свою практику.

    13 июнь 2013, в 16:48

    Поделиться

    Источник

    3 ответа

    Я предполагаю, что вы используете Java версии 1.5. Autoboxing был введен в java 1.5. И ваш код компилируется в java 1.5 +.

    Скомпилировать как источник 1.4:

    javac -source 1.4 A.java
    
    
    A.java:7: error: no suitable method found for add(int)
        list.add(90);
            ^
        method ArrayList.add(int,Object) is not applicable
          (actual and formal argument lists differ in length)
        method ArrayList.add(Object) is not applicable
          (actual argument int cannot be converted to Object by method invocation conversion)
    A.java:8: error: no suitable method found for add(double)
        list.add(9.9);
            ^
        method ArrayList.add(int,Object) is not applicable
          (actual and formal argument lists differ in length)
        method ArrayList.add(Object) is not applicable
          (actual argument double cannot be converted to Object by method invocation conversion)
    A.java:10: error: no suitable method found for add(boolean)
        list.add(true);
            ^
        method ArrayList.add(int,Object) is not applicable
          (actual and formal argument lists differ in length)
        method ArrayList.add(Object) is not applicable
          (actual argument boolean cannot be converted to Object by method invocation conversion)
    3 errors
    

    С 1,5 (или более поздней):

    javac -source 1.5 A.java
    
    warning: [options] bootstrap class path not set in conjunction with -source 1.5
    Note: A.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 warning
    

    Я предлагаю вам обновить java или поместить все примитивы в объекты вручную, как предположил @SoulDZIN.

    Nikita Beloglazov
    13 июнь 2013, в 12:07

    Поделиться

    отлично работает с JDK 6

    public static void main(String[] args) {
                ArrayList list=new ArrayList();
                list.add(90);
                list.add(9.9);
                list.add("abc");
                list.add(true);
                System.out.println(list);
        }
    

    Печатный результат: [90, 9.9, abc, true].

    Если вы используете меньшую версию, чем jdk 6. Укажите версию.

    ꜱᴜʀᴇꜱʜ ᴀᴛᴛᴀ
    13 июнь 2013, в 13:21

    Поделиться

    Обратите внимание, что метод «add» не работает для типов данных:

    int, double и boolean.

    Это все примитивные типы данных, а не «Объекты», ожидаемые методом. Я считаю, что autoboxing не происходит здесь, потому что вы используете литеральные значения, но я не уверен в этом. Тем не менее, чтобы исправить это, используйте связанный тип объекта каждого примитива:

    ArrayList list=new ArrayList();
    list.add(new Integer(90));
    list.add(new Double(9.9));
    list.add("abc");
    list.add(new Boolean(true));
    System.out.println(list);
    

    ИСТОЧНИК: Опыт

    EDIT:

    Я всегда стараюсь указать тип моей коллекции, даже если это объект.

    ArrayList<Object> list = new ArrayList<Object>();
    

    Однако, по-видимому, это не очень хорошая практика, если вы используете Java 1.4 или меньше.

    souldzin
    13 июнь 2013, в 13:13

    Поделиться

    Ещё вопросы

    • 1Нужна помощь, создав диалог с 2 NumberPickers
    • 0Использование ng-параметров с различными объектами в AngularJS
    • 0SQLPro или PostgreSQL SQL обновление строки на основе предыдущего значения строки
    • 1Struts2 — Как перенаправить на действие без использования struts.xml?
    • 0Программа на С ++ показывает очень разное поведение памяти на разных машинах
    • 0Используйте изображение в кредитах Highcharts
    • 0Директива AngularJS для вкладок пользовательского интерфейса BootStrap (проблемы с областью изоляции)
    • 1c # — работа с COM + объектом в WCF
    • 1node.js печатает пользовательский объект перечисления с дополнительным полем [Number], например {[Number: 10] name: ‘Dime’, значение: 10}
    • 0jquery $ .totalStorage — удалить все ключи
    • 1Spring RestTemplate пересылает большой файл в другой сервис
    • 1Webscraping с запросами, возвращающими родительскую веб-страницу HTML
    • 1Пользовательские функции Pandas в возвращении значений столбцов
    • 0AngularFire & Ionic — форма данных не передается на сервер
    • 1Утечка памяти при попытке сохранить ссылку на фрагментное представление за пределы onDestoryView ()
    • 1dojoConfig не может найти ресурсы скрипта при работе на IIS
    • 1Как изменить значение логического значения при нажатии кнопки JButton
    • 1вставить новый экземпляр, используя API GCE
    • 0проверка формы зависит от другого поля
    • 0Почему, когда я пытаюсь скрыть свой треугольник CSS с помощью jQuery, добавив класс, это не работает?
    • 0Очистка угловых частей
    • 1расчет тепловой карты панд на море
    • 0Перенаправление и отметка времени std :: cout
    • 0заставить остановить анимацию конкретного div
    • 1Интеграция служб WCF (ESB?)
    • 1Ограничить Команды
    • 0Использование того же FK в таблицах Mutliple.
    • 1Добавление минут к метке времени в python
    • 0Цвет фона панели навигации не занимает всю ширину
    • 0collect2: ld вернул 1 ошибку состояния выхода
    • 0JQUERY / PLUGIN вызывают функцию извне / аргументы
    • 0Система вкладок для div
    • 1Как сравнить разницу в многомерных массивах?
    • 1Есть ли Java-эквивалент службы Windows
    • 1Как подчеркнуть текст пунктирной линией?
    • 1RxJS запускает функцию выбора только один раз
    • 0Как указать Kohana PHP Частичное представление CSS и JS зависимостей
    • 0Выполнение запроса занимает более 40 секунд
    • 1Android Studio SharedPreferences и внутреннее хранилище не работают
    • 0Как отключить класс css для определенного внутреннего тега div, когда div является фоновым полем?
    • 0Перезаписать / переопределить предупреждение Javascript другим предупреждением
    • 1Когда люди говорят объект, когда они говорят о регулярных выражениях, что они имеют в виду (Python)
    • 1Чтение из нескольких обменов RabbitMQ в клиенте Java не опрос
    • 1Javascript дает недействительный месяц, когда месяц установлен на 5
    • 0Базовое хранилище данных — Как объединить данные на 2 таблицы
    • 1Листовка сделать PolyLine поверх GeoJson
    • 0Создать массив из файла CSV, выбранного по типу файла ввода
    • 0Вставка тегов HTML в переменную PHP [duplicate]
    • 1Как указать дополнительные jar-файлы для задания mr, запускаемого из запросов hive jdbc?
    • 1Экспорт таблицы Excel с сервера в JavaScript

    Сообщество Overcoder

    Понравилась статья? Поделить с друзьями:
  • Light path diagnostics расшифровка ошибок
  • Lifan x60 ошибка svs
  • Lg ошибка ue как открыть дверь
  • Lexus ошибка c1532
  • Lexus is 250 ошибка p0420