How would I switch from an Array to an ArrayList?
This question already has an answer here:
To change code that uses an array into code that uses an ArrayList
:
Instead of a[i]
, when it's not on the left side of an assignment, use a.get(i)
Instead of a.length
, use a.size()
Instead of setting a[i] = expression
: if i
is known to be in range (0 <= i
<= a.length-1
), use a.set(i, expression)
. If i == a.length
, you couldn't use a[i] = expression
with an array, but you can do it with an ArrayList
, increasing the size by 1: a.add(expression)
. If i > a.length
, so that you want to add a new element in the ArrayList
leaving a gap, then something like:
while (a.size() < i)
a.add (null);
// at this point a.size == i
a.add (expression);
// now a.size == i+1
That should cover all the basic operations on arrays. There are some utility operations defined in Arrays
that don't have equivalent operations in ArrayList
, like binarySearch
.
I use LinkedList, it's very similar to ArrayList. You declare it like this:
LinkedList<Student> StudentList = new LinkedList<Student>();
Then you can add students like this:
StudentList.add(newStudent(id,name,major,gpa,campus,address,number,email,current,past,future,notes))
Then you can remove students like this:
StudentList.remove(Student student1);
You can also clear all the students from the list,if needed, like this:
StudentsList.clear();
Hope this helps!
链接地址: http://www.djcxy.com/p/17640.html上一篇: 将数组更改为ArrayList
下一篇: 我将如何从一个数组切换到一个数组列表?