Katherine
Katherine

Reputation: 257

delete item in arraylist

I'm writing a method to remove the minimum item from an arrayList. I have found the minimum item correctly, however, I don't have any clue on the removing method to be honest, I believe the second half of my code is completely useless. Any help is appreciated!

  public Comparable remove(){
      Iterator<T> iterator=iterator();
      T min = iterator.next();
      while (iterator.hasNext())
      {  
         T next = iterator.next();
         if (min.compareTo(next) > 0) 
            min = next;
            size--;
            **Bag<T> newBag=new Bag<T>();
            for (int i=0; i<size;i++){
                newBag=(Bag<T>) data[i];
                System.out.println(newBag);**
            }
      }
    return min;
  }

Upvotes: 2

Views: 117

Answers (4)

Muhammad Shuja
Muhammad Shuja

Reputation: 672

You can do it easily by using built-in functions.

For ArrayList use Collections.min(Name_Of_ArrayList);

It will give you the smallest object in ArrayList, save that value in an Object variable

You can, then, remove it by using Name_Of_ArrayList.remove(Object);

Here's the code:

Object minimum= Collections.min(Name_Of_ArrayList);
Name_Of_ArrayList.remove(minimum);

Upvotes: 0

dsharew
dsharew

Reputation: 10675

Using Iterator is good idea (it is thread safe) but you dont need to use interator here because you are not modifying the list as you iterate, also you dont need to sort the list to find the minmum element because that is expensive.

What you have tried is good though dont understand some of your code but try like this:

 public void remove(List<T> list){

    T min = Collections.min(list);

    list.remove(min)

  }

Upvotes: 2

Raphael Amoedo
Raphael Amoedo

Reputation: 4475

You can get the minimum value from a list doing:

Collections.min(list);

And then you can remove from a list:

list.remove(Collections.min(list)));

Upvotes: 2

ndmhta
ndmhta

Reputation: 536

We can remove an object from ArrayList. What you should do is keep track of the index at which you find minimum value and then remove that element.

e.g.

arrayList.remove(index);

Upvotes: 1

Related Questions