Ahm
Ahm

Reputation: 11

Remove element from an ArrayList after getting it

I have a method that takes the first element of an ArrayList and puts it into another ArrayList.

Let's say that A = {1, 2, 3} and C = {}

After the method getStudent() my lists now look like this:

A = {1, 2, 3} and C = {1}

Is there a way, using ArrayLists, to have the 1 disappear from list A as soon as it is passed to C?

My code:

public Disk getStudent() {

// so it gives me element 0
    Student topStudent = studentCollection.get(studentCollection.size() - studentCollection.size());
    return topStudent;
}

I know you can do something like this with stack, but I need this particular piece to be an ArrayList.

Upvotes: 0

Views: 64

Answers (5)

Matija P.
Matija P.

Reputation: 1

You can define custom get method in which remove element from the list before returning.

For example:

public Student getFrstStudentFromList(){
    if(studentCollection.size()!=0){
        Student topStudent = studentCollection.get(0);
        studentCollection.remove(topStudent); // or studentCollection.remove(0);
        return topStudent;
    }
    return null;
}

another way

ArrayList<Student> list1 = new ArrayList<>();
ArrayList<Student> list2 = new ArrayList<>();
list1.add(new Student("Student 1"));
list1.add(new Student("Student 2"));
list1.add(new Student("Student 3"));

moveFrstElementFromList1ToList2(list1,list2);

public static void moveFrstElementFromList1ToList2(ArrayList<Student> l1, ArrayList<Student> l2){
    if(l1.size()!=0){
        l2.add(l1.get(0));
        l1.remove(0);
    }
}

I hope this may help you

Upvotes: 0

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

You have two ways to achieve this

  1. Use List.remove(0) to delete the element after fetching it and adding it to another list.

  2. Use queue instead of list for the lists. that way you can do something like - C.add(A.poll())

Upvotes: 0

Chili
Chili

Reputation: 154

if your function return an object, you can use it to remove the element from the ArrayList

yourArrayList.remove(getStudent());

Upvotes: 0

nbpeth
nbpeth

Reputation: 3148

Does it happen linearly? If so, you could use a stack or a queue and pop or dequeue respectively and and then add the result to the new list. Otherwise, you'll want to have three operations - store the value from studentCollection, remove it from studentCollection and then add the value to the new list.

Upvotes: 1

Makoto
Makoto

Reputation: 106410

In place of get, use remove.

Also, note that by subtracting the collection's size from itself, you're getting 0, so it's simpler to write the following:

studentCollection.remove(0);

Upvotes: 2

Related Questions