Class ArrayList
Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)
The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(. ));
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class is a member of the Java Collections Framework.
NullPointerException при добавлении объекта в ArrayList
Здравствуйте! Проблема в том, что при добавлении объекта в список ArrayList, моя программа выдаёт java.lang.NullPointerException. Код прилагается, помогите разобраться пожалуйста .
public class Main { public static void main(String[] args) { Gui gui = new Gui("Морской бой"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
import javax.swing.*; import java.util.ArrayList; public class Gui extends JFrame { int i; ArrayListButton> buttonsList; JFrame gui = new JFrame(); Button but; int xGrid; public Gui(String title){ super(title); defaultOperation(); paintCells(10, 10, 20, 20); setVisible(true); } private void paintCells(int xLoc, int yLoc, int xSiz, int ySiz){ int xLocM = xLoc; while (i 100){ but = new Button(); but.setLocation(xLocM, yLoc); but.setSize(xSiz, ySiz); buttonsList.add(but); //Вот тут выдаёт ошибку add(but); i++; if (xGrid 9){ xLocM = xLoc + (xSiz * (xGrid + 1)); xGrid++; } else{ yLoc = yLoc + ySiz; xGrid = 0; xLocM = xLoc; } } } public void defaultOperation(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setLocationRelativeTo(null); setResizable(false); setLayout(null); } }
Класс Button просто расширяет JButton, добавляя пару переменных, которые я потом буду запрашивать у кнопки.
Ошибка java.lang.NullPointerException при добавлении записи в базу данных
Здравствуйте! Подскажите, пожалуйста, почему 15-ая строка возвращает нулевое значание? Что не так.
При создании нового объекта класса NullPointerException
Добрый день. Есть два класса // содержит индексы для таблицы public class Slot < .
Мерцание при рандомном добавлении объекта
Добрый день.нарисовал анимацию,нужно рандомно добавить дерево,но когда оно добавляется начинает.
При добавлении объекта приложение выпадает ошыбка
Раньше был вот такой код (приведен ниже) для выделения диапазона ячеек. Range("A1").Activate.
java.lang.NullPointerException in ArrayList
posted 4 years ago
How to fix NullPointerException in ArrayList
posted 4 years ago
I think you get this exception because you declared classList but you haven’t initialized it. You should change your classList as:
posted 4 years ago
posted 4 years ago
No. If you initialize classList in displayStudents() method, you create a local classList with size 0 and it overrides your instance variable classList. You should initialize it where you declare it.
posted 4 years ago
Ekrem Candemir wrote: No. If you initialize classList in displayStudents() method, you create a local classList with size 0 and it overrides your instance variable classList. You should initialize it where you declare it.
posted 4 years ago
- 1
posted 4 years ago
posted 4 years ago
You declared classList on line 11 but you haven’t initialized it yet. You can initialize it saying and you must delete line 64.
You don’t add any elements in classList by the way, so you get 0 when you call classList.size().
Also, if you use your ArrayLists with generics then you don’t need to casting your elements to Student. You can do it this way:
If you do this change, then you can change line 67 like this:
I’m not a native speaker, I hope you understand what I mean.
posted 4 years ago
Saloon Keeper
posted 4 years ago
You seem to be trying to do both arrays and Lists for the same thing. Use just the Lists and do away with the arrays entirely. And based on how you are using classList later in the program, it seem that it more like a studentList.
Then you can replace
with
Marshal
posted 4 years ago
I’d go back to line 8. Why do you extend Student with EnrollmentMain? Does EnrollmentMain is a Student? Sure it isn’t!
I feel that you are in a rush with this exercise.
The problem you are currently facing, that you don’t have methods you could trust. Again, that happens when you are in a rush and write more and more code without even testing them whether individually they produce the expected output.
For example. You have methods displayStudents and displayStudent. So looking to these names, I’d expect that method displayStudents would call method displayStudent as many times as many students there are, however, that’s not the case — so something is not quite right there.
In these JOptionpanes you wouldn’t need to have these long concatenations to print student details if you were implement (by overriding) toString() method in a Student class (probably as well as in Subject). Since you were introduced to OO concepts I presume already, you should be knowing that. So why you don’t do that and complicating things that much for yourself?
I personally wouldn’t try to solve these singular small issues which are just symptoms of other bigger problems: in program’s design, structure. I’d start from there first.
Class ArrayList
Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)
The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(. ));
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class is a member of the Java Collections Framework.