Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive types in collections

 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are there collections (apart from arrays)which hold primitive types without having to use wrappers
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48642
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If toArray() returns an Object, try casting that Object to byte[].
CR
 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that won't let me

error: Cannot cast from Object[] to byte[]
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try...
 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have


The method toArray() in the type List<Byte> is not applicable for the arguments (byte[])
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no way to do it without an explicit loop, something like



Probably want to store list.size() in a variable, first.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic