Skip to main content

(Not So) Stupid Questions 20: Primitives and Collections

November 27, 2007








Editor's note: Sometimes the most interesting discussions begin when someone says, "This may be a stupid question, but ...." If the person asking the question has taken the time to think about the problem before asking, the question is often not stupid at all. The uncertainty points out an ambiguity in the specs, holes in the docs, or a search for how more experienced programmers might address a particular problem. From time to time, we will print one of the "(Not So) Stupid Questions" we receive and invite our readers to answer the question in the feedback section.

Remember that new people are joining the Java community all the time and may be looking for help from those with more experience. Also, those who began with Java as their first language can benefit from those coming to the community with experience in other languages. As always, answer the questions with kindness. You are also welcome to submit your questions to

This may be a stupid question, but ... "Can you really not use primitives in a collection?"

First Thoughts

In an attempt to understand boxing and unboxing, I was rooting around on the Java.sun.com site, and found the J2SE 5.0 page on Autoboxing.

On the first line, it says:

As any Java programmer knows, you can't put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int).

So I tried testing it out with the following code:

      public void boxItPrimitive(){
            int first = 1;
            int second = 2;
            int third = 3;
            ArrayList listONumbers = new ArrayList();
            listONumbers.add(first);
            listONumbers.add(second);
            listONumbers.add(third);
            for(int i=0; i< listONumbers.size(); i++){
                  System.out.println(listONumbers.get(i));
            }
      }
ArrayList implements the interface Collection, yet there are no Integers, just ints. To my surprise, I was able to compile and run this method!
The output was:

1
2
3

Is there a reason I can input raw primitives into a collection without boxing them?


width="1" height="1" border="0" alt=" " />
Related Topics >> Programming   |