- Java – Ошибка при удалении из ArrayList более одного раза. (IllegalStateException)
- Что за хрень?
- Why i’m getting ArrayIndexOutOfBoundsException in arraylist?
- [Solved]: javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context
- Вычитание одного arrayList из другого arrayList
Java – Ошибка при удалении из ArrayList более одного раза. (IllegalStateException)
Я немного искал поисковую систему и не мог найти решение. Что я тут сделал? Моя проблема в названии. Вот исключение, которое я получаю:
java.lang.IllegalStateException at java.util.ArrayList$Itr.remove(Unknown Source) at me.herp.derp.client.Config.updateItem(Config.java:24) at me.herp.derp.client.Commands.parseCommand(Commands.java:23) at me.herp.derp.client.ChatCommands.handleChatcommand(ChatCommands.java:29) at net.minecraft.src.EntityClientPlayerMP.sendChatMessage(EntityClientPlayerMP.java:171) at net.minecraft.src.GuiChat.keyTyped(GuiChat.java:104) at net.minecraft.src.GuiScreen.handleKeyboardInput(GuiScreen.java:227) at net.minecraft.src.GuiScreen.handleInput(GuiScreen.java:176) at net.minecraft.client.Minecraft.runTick(Minecraft.java:1494) at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:843) at net.minecraft.client.Minecraft.run(Minecraft.java:768) at java.lang.Thread.run(Unknown Source)
public static void updateItem(String item, String value) < if (!hasValue(item)) < addItem(item, value); return; >for (ConfigItem c : configItems) < if (c.ITEM.equals(item)) < configItems.iterator().remove(); break; >> ConfigFile.saveConfig(); >
Итератор не был инициализирован правильно ( next() не был вызван). Я предлагаю написать этот код следующим образом:
Iterator it = configItems.iterator(); while(it.hasNext()) < ConfigItem c = it.next(); if (c.ITEM.equals(item)) < it.remove(); break; >>
Вы можете вызвать Iterator.remove() только после Iterator.next(). Попробуйте следующее:
Iterator i = configItems.iterator(); while(i.hasNext())
Что за хрень?
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.updateControllerButton(JoypadConfigMenu.java:291)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.toggleController(JoypadConfigMenu.java:282)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.func_73875_a(JoypadConfigMenu.java:146)
at net.minecraft.client.gui.GuiScreen.func_73864_a(SourceFile:69)
at net.minecraft.client.gui.GuiScreen.func_73867_d(SourceFile:128)
at net.minecraft.client.gui.GuiScreen.func_73862_m(SourceFile:107)
at net.minecraft.client.Minecraft.func_71407_l(Minecraft.java:1566)
at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:910)
at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:838)
at net.minecraft.client.main.Main.main(SourceFile:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:131)
at net.minecraft.launchwrapper.Launch.main(Launch.java:27)
— Head —
Stacktrace:
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.updateControllerButton(JoypadConfigMenu.java:291)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.toggleController(JoypadConfigMenu.java:282)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.func_73875_a(JoypadConfigMenu.java:146)
at net.minecraft.client.gui.GuiScreen.func_73864_a(SourceFile:69)
at net.minecraft.client.gui.GuiScreen.func_73867_d(SourceFile:128)
at net.minecraft.client.gui.GuiScreen.func_73862_m(SourceFile:107)
— Affected screen —
Details:
Screen name: com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu
Stacktrace:
at net.minecraft.client.Minecraft.func_71407_l(Minecraft.java:1566)
at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:910)
at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:838)
at net.minecraft.client.main.Main.main(SourceFile:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:131)
at net.minecraft.launchwrapper.Launch.main(Launch.java:27)
Или моды не местимые, или java нету, также есть вероятность что все моды просто не тянет твой компьютер.
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.updateControllerButton(JoypadConfigMenu.java:291)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.toggleController(JoypadConfigMenu.java:282)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.func_73875_a(JoypadConfigMenu.java:146)
at net.minecraft.client.gui.GuiScreen.func_73864_a(SourceFile:69)
at net.minecraft.client.gui.GuiScreen.func_73867_d(SourceFile:128)
at net.minecraft.client.gui.GuiScreen.func_73862_m(SourceFile:107)
at net.minecraft.client.Minecraft.func_71407_l(Minecraft.java:1566)
at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:910)
at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:838)
at net.minecraft.client.main.Main.main(SourceFile:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:131)
at net.minecraft.launchwrapper.Launch.main(Launch.java:27)
— Head —
Stacktrace:
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.updateControllerButton(JoypadConfigMenu.java:291)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.toggleController(JoypadConfigMenu.java:282)
at com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu.func_73875_a(JoypadConfigMenu.java:146)
at net.minecraft.client.gui.GuiScreen.func_73864_a(SourceFile:69)
at net.minecraft.client.gui.GuiScreen.func_73867_d(SourceFile:128)
at net.minecraft.client.gui.GuiScreen.func_73862_m(SourceFile:107)
— Affected screen —
Details:
Screen name: com.shiny.joypadmod.minecraftExtensions.JoypadConfigMenu
Stacktrace:
at net.minecraft.client.Minecraft.func_71407_l(Minecraft.java:1566)
at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:910)
at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:838)
at net.minecraft.client.main.Main.main(SourceFile:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:131)
at net.minecraft.launchwrapper.Launch.main(Launch.java:27)
Why i’m getting ArrayIndexOutOfBoundsException in arraylist?
posted 6 years ago
I have commented out lines 12 & 13.
When I add line 12 to the program, it throws arrayindexoutofboundsexception.
But when I remove line 12 & add line 13 to the program, it throws indexoutofboundsexception.
Why does line12 throw arrayindexoutofboundsexception while i’m dealing with ArrayList?
output when i add line12 in the program.
output when i add line13 instead of line12 in the program.
posted 6 years ago
Correction: i’ve typed line 12 and 13 for line 13 and 14.
Please consider line 13 where i’ve mentioned line 12 and line 14 where i’ve mentioned line 13.
posted 6 years ago
Hi gautham,in java array index starts from 0,so if you code like this-a.get(-1),you are requesting arraylist to give you the element at index -1 which is out of bound of arraylist index or illegal index(means index is either negative or greater than size of array) in java,so you get the exception ArrayIndexOutOfBoundsException,but if you will request the arraylist to give you the element at out of range index then you will get IndexoutOfBoundsException.
Actually arraylist uses an array backing for storing the elements and you can define its initial capicity during initialization and it will grow its size by itself when elements exceeds the initial capicity resulting in growing the size.
See these link for further understanding-oracle api—>IndexOutOfBoundsException , ArrayIndexOutOfBoundsException , ArrayList.
Try to enjoy your work while doing it,it will Automatically convert in Hard Work.
[Solved]: javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context
This exception occur when you are using JAXB to marshal a java object (collection type) to xml format. The stack trace looks like this:
Exception in thread "main" javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context. at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source) at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58)
The above exception occurs because JAXB always expects a @XmlRootElement annotation on the entity, it gets to marshal. This is mandatory and can not be skipped. This @XmlRootElement annotation is required to get meta data from root element of XML marshalled from java object.
ArrayList class OR any java collection class does not have any JAXB annotations on it. Due to this JAXB is unable to parse any such java objects and raises this error.
Solution : Create wrapper class
This is recommended approach because it gives you flexibility to add/remove fields in future e.g. size attribute.
@XmlRootElement(name = "employees") @XmlAccessorType (XmlAccessType.FIELD) public class Employees < @XmlElement(name = "employee") private Listemployees = null; public List getEmployees() < return employees; >public void setEmployees(List employees) < this.employees = employees; >>
Now you can use this class as below:
static Employees employees = new Employees(); static < employees.setEmployees(new ArrayList()); Employee emp1 = new Employee(); emp1.setId(1); emp1.setFirstName("Lokesh"); emp1.setLastName("Gupta"); emp1.setIncome(100.0); Employee emp2 = new Employee(); emp2.setId(2); emp2.setFirstName("John"); emp2.setLastName("Mclane"); emp2.setIncome(200.0); employees.getEmployees().add(emp1); employees.getEmployees().add(emp2); > private static void marshalingExample() throws JAXBException < JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(employees, System.out); >Output:1 Lokesh Gupta 100.0 2 John Mclane 200.0
Happy Learning !!
Вычитание одного arrayList из другого arrayList
У меня есть два массива, и я пытаюсь «вычесть» один массивList из другого. Например, если у меня есть один массивList [1,2,3] , и я пытаюсь вычесть [0, 2, 4] , то resultList должен быть [1,3] . Мой код работает в некоторых случаях, например, если arrayList1 = [4,6] и arrayList2 = [6] он даст мне результат [4] . Но если я попробую что-то вроде [1,2,4] и [0,4,8] Я получаю это исключение:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at IntSet.minus(IntSet.java:119) at IntSetDriver.main(IntSetDriver.java:62)
Вот код, который я придумал. Я проделал тест через него, и мне кажется, что он должен работать. Пользователь вводит эти списки массивов, и они предварительно настроены, я также не знаю Hash или big-O.
ArrayList minusArray = new ArrayList(); minusArray.addAll(array1); for(int i =0; i < minusArray.size(); i++)< for(int j = 0; j < array2.size(); j++)< if(minusArray.get(i).equals(array2.get(j)))< minusArray.remove(i); >else<> > > return minusArray;
Так как ваш код проверяет equals() для каждого элемента в массиве и удаляет, if true . Вы можете просто использовать removeAll() как предложено в этом ответе: stackoverflow.com/a/23172547/1485527 . Или я что-то упустил? Если вы хотите удалить только первое вхождение, используйте Apache Utils или просто Java, как предложено здесь stackoverflow.com/a/49415419/1485527 . В противном случае я бы хотел предложить ваше решение в форме ответа и объяснить, почему оно лучшее. Включение ответа в вопрос перерывает стиль вопросов и ответов.