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)
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)
You can use the Object
type:
for (Object obj:al){}
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!