0

How to use for each loop in java if there has multiple datatypes in an array?

My code so far:

ArrayList al=new ArrayList();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
al.add(123);
al.add(456);

for(??? obj: al)
GhostCat
  • 137,827
  • 25
  • 176
  • 248
teja
  • 93
  • 2
  • 11

2 Answers2

4

You can use the Object type:

for (Object obj:al){}
anon
  • 1,258
  • 10
  • 17
  • Thanks. its running but iam getting following message in console :java uses unchecked or unsafe operations. – teja Jul 24 '17 at 07:29
  • That is a warning and not an error so the code will still compile. Let me check what I get and get back to you – anon Jul 24 '17 at 07:34
  • All the warnings I got were just saying to parameterize the generic type of the `ArrayList` which went away by parametrizing when initializing it like: `ArrayList al=new ArrayList();` – anon Jul 24 '17 at 07:38
  • Thanks @priyaraj . now its not showing any warnings – teja Jul 24 '17 at 07:41
1

The real answer here: step back and learn about generics.

The various issues you are facing are caused by one simple thing: you have not much clue of what you are doing.

First of all, you were using a raw type (by not providing a type parameter to your list). Ideally, lists are used like this:

List<Whatever> items = new ArrayList<>();

In your case, Whatever should be Object.

But then: your idea of having different things in the same list might already be bad practice. You see, collections are providing you generics, to explicitly say: "I have a list of X". And then you can be assured that only X objects are in that list.

In other words: having List<Object> is something that you normally want to avoid. You want that the compiler helps you to understand what kind of objects you have in that list!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • thank you. you are absolutely right .i am new to collections as unaware of many things that needs to be learn. – teja Jul 24 '17 at 11:36