1

i have an ArrayList which contains String elements and i want to add an int into the list but with out Converting that into the String is that possible.

i have tried this and this is working too.

int a1 = 10;
java.util.List list = new ArrayList<String>();
list.add(a1);
System.out.println("List element"+list.get(0));

and but i am wondering this to be happen.

int a1 = 10;
java.util.List<String> list = new ArrayList<String>();
            list.add(a1);
            System.out.println("List element"+list.get(0));

is that possible to do?

4
  • 3
    No.. You shouldn't do it.. You can add anything if the list is raw.. But still its not a good practice.. Commented Feb 20, 2014 at 7:25
  • 1
    No it isn't, unless you have a List<Object> And even then you'd need to .add(new Integer(a1)) since int is not a class. Commented Feb 20, 2014 at 7:25
  • 1
    What would be the point of having a list of strings (List<String>) if you can put anything inside it? The whole point of generics is to provide type-safety. Commented Feb 20, 2014 at 7:28
  • @fge that is not bad ans. actually its partially 90% right ans. :) so +1 for you. Commented Feb 20, 2014 at 7:44

4 Answers 4

5

try this

 list.add(String.valueOf(a1));
Sign up to request clarification or add additional context in comments.

Comments

1

An advantage of a typed list is, that you can assume, that you only have objects of the given type in the list - why would one want to throw this advantage away, if it is completely easy to convert the given type into the type of the list?

1 Comment

I agree dude but its just for knowledge any ways +1 for your ans. :)
1

In first case your List is just a raw List. So you can add what ever type to that since List is raw and again that is bad way of use of List in Java..But second case it is String List you have to add Stings there.

Now you have to use following way to add int to List.

 int a1 = 10;
 java.util.List<String> list = new ArrayList<String>();
 list.add(String.valueOf(a1)); // now String value of int will add to list
 System.out.println("List element"+list.get(0));

Comments

1

You can not do it without converting it to String, but one alternate way to do it by String concatination(without direct conversion from int to String):

list.add("" + a1);

but internally it will append a1 value to "" String and final result is String.

1 Comment

It converting that value into the String it self bro. :) i dont want it. but ya +1 for your response.

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.