2

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;
  }

4 Answers 4

2

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)));
Sign up to request clarification or add additional context in comments.

Comments

2

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)

  }

Comments

1

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);

Comments

0

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);

1 Comment

This is not a good idea, as it is not very efficient. You can find the minimum by iterating the list once (which is O(n)), while sorting runs in O(nlgn) at best.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.