0

I have a question regarding to remove method in arraylist in java, for example:

 ....
 ArrayList<Array>list=new ArrayList<Array>();



 Array a=new Array (1,2,3);
 Array b=new Array (4,5,6);
 Array c=new Array (7,8,9);

 list.add(a);
 list.add(b);
 list.add(c); 
 ....

My question is, if I want to remove object b from the arraylist, should I use list.remove(1) or list.remove(b)? In another way, should I use object or index for the parameter in the remove method in this case?

7
  • 5
    Both remove methods are implemented. Why don't you read the doc ? docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html Commented Nov 12, 2013 at 15:32
  • possible duplicate of Remove Item from ArrayList Commented Nov 12, 2013 at 15:33
  • 1
    @ZouZou Because both work and the question is which of them would be the better choice. Commented Nov 12, 2013 at 15:34
  • You'd better use list.remove(b), it's more java-like but it's always the same : if you can do both then it means that both may be useful, depending on the use case. In other words it's up to you man :) Commented Nov 12, 2013 at 15:34
  • 1
    @blalasaadri IMO the question doesn't make any sense if you don't do some research first, and the research is: reading the docs, do some testing... which the question doesn't show at all. Commented Nov 12, 2013 at 15:41

2 Answers 2

3

You can use both, but obviously better will be deleting object, as the order theoretically might change.

EDIT: As @Luiggi Mendoza mentioned - just remember to override equals() method, if you want to properly use remove(Object o). And if you do, don't forget to also override hashCode().

Sign up to request clarification or add additional context in comments.

6 Comments

In order to use List#remove(Object o) the class should implement equals method, and by implementing it the class also should implement hashCode as well...
Not only could it change, if you remove several objects the order will probably change unless you remove them in reverse order. So using remove(Object) will be the better choice in most cases.
The order of the list could change?!
@CharlesForsythe that may happen if you use List#add(int index, E e)
@LuiggiMendoza I think I see what you're saying. I would not describe that at the order changing, so the description confused me.
|
0

You can do both, removing with the index or the object him self

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.