-7

I have an Arraylist, for example

ArrayList<SomeType> newObjectList = new ArrayList<>();

I want to use an object from the Arraylist without using the method remove. I don't want to remove the object from the list, just to refer to it and use its methods.

How can I do this? Thanks.

4
  • 1
    So do so; what's the specific issue? Commented Mar 9, 2017 at 13:22
  • 3
    I'm afraid I have no idea what your issue/question is. Commented Mar 9, 2017 at 13:23
  • I think OP wants to get a reference to an object from the list and when he sets that reference to null, the object must still be in the list. Or at least this is what I got from his explanation Commented Mar 9, 2017 at 13:26
  • 4
    when looking for desired functionality the public API documentation could be a useful resource... docs.oracle.com/javase/8/docs/api/java/util/List.html Commented Mar 9, 2017 at 13:28

2 Answers 2

5

Use the method newObjectList.get(index) instead

Documentation

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

Comments

0

You can disable the remove method using the Collections.unmodifiableList() construct:

List<Object> newObjectList = Collections.unmodifiableList(new ArrayList<Object>());

This will throw an UnsupportedOperationException when trying to add or remove an object.

2 Comments

I don't think the OP is asking to restrict removal, rather to reference a list item without removing it.
I don't know OP is asking for :) I.e. just referencing it without removing it - it's so simple, that nobody should ask that on SO. Thus I made a guess, like this might be relevant too.

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.