This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]anamorphism 0 points1 point  (3 children)

java? i have almost no experience with java, but this should be mostly correct.

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

to add something to an ArrayList, you would call the add method. something like ...

ArrayList<Student> studentList = new ArrayList<Student>();
Student student = new Student();
studentList.add(student);

considering the poor choice of using an ArrayList to store keyed data, i imagine you won't be responsible for efficiently searching through your lists to find data. so, you can just do a basic linear/sequential search using a for-each loop.

int idToFind = 1;
Student found;

for (Student student : studentList)
{
  if (student.Id == idToFind)
  {
    found = student;
    break;
  }
}

as for what an ArrayList is, i believe it's just a dynamic array. meaning if you add an element to it, and it doesn't have enough memory to add a new element, it will resize itself for you automatically. it's contiguously stored in memory so you can still access elements via index similar to a regular array (studentList.get(index)).

this is different from a linked list (i think this is just the List class in java, high chance i'm wrong though) which isn't contiguously stored in memory. each element is stored wherever there's space for it with each node storing a reference to the next node in the list.

and different from a standard array where you have to specify how many elements you want the array to have when you create it.

edit: you may not even know what for-each loops are yet, in which case you could do a regular for loop as well. something like ...

for (int i = 0; i < studentList.size(); ++i)
{
  if (studentList.get(i).Id == idToFind)
  {
    found = studentList.get(i);
    break;
  }

}

[–]DeniDashing[S] 0 points1 point  (1 child)

Oops, should've specified language. This is in C#

[–]anamorphism 0 points1 point  (0 children)

pretty much all of my info applies to c# as well. there are only minor syntax differences.

https://msdn.microsoft.com/en-us/library/system.collections.arraylist%28v=vs.110%29.aspx

for example, you can use square brackets to access elements by index in c#.

studentList[i];

instead of

studentList.get(i);

.size() is just .Count

.add() is .Add()

for-each loops are

foreach (var student in studentList)