GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes primitive types in collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "primitive types in collections" Watch "primitive types in collections" New topic
Author

primitive types in collections

Nikos Stavros
Ranch Hand

Joined: Feb 24, 2006
Posts: 243

are there collections (apart from arrays)which hold primitive types without having to use wrappers


Jesus lives
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

In Java 5, you can put primitives into all the java.util collections, and the wrappers will be created/extracted automatically. This feature is called "autoboxing" -- try it!

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
int two = list.get(1);

There are primitive collection libraries that third parties have written -- Google "sosnoski typesafe collections" to find one that I've used.


[Jess in Action][AskingGoodQuestions]
Nikos Stavros
Ranch Hand

Joined: Feb 24, 2006
Posts: 243

ok that worked thanks

Now I have an ArrayList of Byte objects. How do I turn this into a byte[] array without doing it manually by iteration. I tried toArray() but it returns an object
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39079
    
  23
If toArray() returns an Object, try casting that Object to byte[].
CR
Nikos Stavros
Ranch Hand

Joined: Feb 24, 2006
Posts: 243

that won't let me

error: Cannot cast from Object[] to byte[]
Petrus Pelser
Ranch Hand

Joined: Feb 20, 2006
Posts: 132
Try...
Nikos Stavros
Ranch Hand

Joined: Feb 24, 2006
Posts: 243

I have


The method toArray() in the type List<Byte> is not applicable for the arguments (byte[])
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

There's no way to do it without an explicit loop, something like



Probably want to store list.size() in a variable, first.
 
 
subject: primitive types in collections