1

Say I have the following two empty lists

List<String> obj1 = new ArrayList<String>();
List< Integer> obj2 = new ArrayList<Integer>();

without foreknowledge, how can I tell which is of type String and which is of type Integer? (Please, never mind why I need this info).

Here I can no longer do

if (!list.isEmpty() && list.get(0) instanceof String)

as the list is empty.

learner
  • 11,452
  • 24
  • 87
  • 160
  • 8
    If it is a local variable, **you can't**. And basically you now have to change _Please, never mind why I need this info_. – Sotirios Delimanolis May 22 '14 at 17:58
  • 3
    This is not possible. I also find that situations like this may also point to a design flaw. – Leon May 22 '14 at 17:59
  • @SotiriosDelimanolis, I am just trying to avoid the barrage of comments about what it's for, etc. But the list is relayed through the update method of an observer, where the observable can send either content type. – learner May 22 '14 at 18:01
  • This might help http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime – codingenious May 22 '14 at 18:01
  • You're declaring the lists explicitly yourself, so you _have_ foreknowledge in this example (ie you know `obj1` contains Strings). If the lists are passed to your objects at runtime, you cannot determine this without a hideous `instanceof`. – jahroy May 22 '14 at 18:03
  • I agree with @Leon that your design smells bad. – jahroy May 22 '14 at 18:04
  • You've explained what you want to do with it: _But the list is relayed through the update method of an observer, where the observable can send either content type._, but not why. – Sotirios Delimanolis May 22 '14 at 18:06
  • If you tell us more about what you need to do, people will be able to suggest a better design quickly. – jahroy May 22 '14 at 18:14
  • 2
    Even if the `List` is not empty, the fact that one element is `instanceof` `X` does not prove that the `List` is a `List` – Holger May 22 '14 at 18:15
  • Collections don't have a content type (Check out for example the source of ArrayList, its all Object internally). So you can't check it. Pass the type along with the list if you need it. – Durandal May 22 '14 at 18:28

1 Answers1

-2

This is not a correct approach, but it works!

List<String> obj1 = new ArrayList<>();    
List<Integer> obj2 = new ArrayList<>();

Object o = new Integer(7);
try{
  obj1.add((String) o);
  System.out.println("This is a list of integer!");
}catch(ClassCastException ex){
  System.out.println("This is not a integer list!");
}