2

I got an array with Objects. Now I want to check if all of those Objects are instance of MyObject.

Is there a better option than this:

boolean check = true;
for (Object o : justAList){
  if (!(o instanceof MyObject)){
    check = false;
    break;
  }
}
5
  • Could you also provide the example array? Commented Jun 30, 2015 at 15:18
  • @ChrisSprague idk, I don't want to have a loop there, because I loop through it after that again. Commented Jun 30, 2015 at 15:18
  • because I loop through it after that again Can't you check it in the same loop??? Commented Jun 30, 2015 at 15:20
  • Can't you then merge these two loops? Commented Jun 30, 2015 at 15:20
  • @AbishekManoharan I don't want to do something if there is any object from the superclass in it. Kind of Transanction Style: do it witch every or none. Commented Jun 30, 2015 at 15:21

3 Answers 3

6

If you don't like the loop, you can always do this in Java 8:

Using ArrayList

List<Object> justAList = new ArrayList<>();
// Add items here...
return justAList.stream().allMatch(o -> o instanceof MyObject);

Using normal array

Object[] justAList = new Object[10];
// Set items here...
return Arrays.stream(justAList).allMatch(o -> o instanceof MyObject);

EDIT:

The above suggestion will only be useful to you if you want to perhaps improve code readability and/or make it more succinct. But don't think that it avoids having to perform a loop. It will still perform a loop, you just won't see it. So don't expect this to perform any better than what you already have.

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

1 Comment

Well, you said list, so I assumed you were using an ArrayList. I'll edit my post to give you both an ArrayList version, and an array version. EDIT: Sorry, I just noticed that the text of your post did say array :) It would have helped to have included the type in your code though.
1

It might not relate to this particular problem, but it is a good practice to use polymorphism instead of checking the type in an if condition. Like

 public void handle(MyObject object) {
   doSomething
 }
 public void handle(Object object) {
   doSomething
 }


 handle(o);

Comments

0

Depending on your requirements, you could use a List<MyObject> and other Lists with their respective types in the first place instead of an Object-Array in which you put everything.

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.